Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This answer is for static pages and files since static urls is not really a problem with node.js, and it's covered here at the <a href="http://expressjs.com/guide.html" rel="nofollow">express js guide</a>.</p> <p>Using only node.js without any framework is a pretty bad idea if you're going to build a webapp. However, there are lots of good webframeworks for node.js that makes life a lot easier. If you've got <a href="https://github.com/isaacs/npm" rel="nofollow">NPM</a> installed they are really easy to include too.</p> <p>I've only got experience with <a href="http://expressjs.com/" rel="nofollow">express.js</a> but it makes it really easy to create webapps if you've got any previous experience with any MVC type web-framework.</p> <p>From my experience it's true that there is no way to serve static pages built in to node.js. However, building a controller that can serve static pages it really simple.</p> <p>Here is an example using express.js.</p> <p><strong>server.js</strong> </p> <pre><code>... app.get('/content/*', controllers.content.getfile); ... </code></pre> <p>This creates a route that captures every url going to the <code>content</code> directory and directs it to the action getfile in the content controller i.e. www.yourdomain.com/content/style.css</p> <p><strong>controllers.js</strong></p> <pre><code>... exports.content = { getfile : function(req,res){ var uri = url.parse(req.url).pathname; var filename = path.join(process.cwd(), uri); path.exists(filename, function(exists){ if(!exists){ res.writeHead(404, {"Content-Type" : "text/plain"}); res.write("Content not found"); res.end(); return; } fs.readFile(filename, "binary", function(err, file){ res.writeHead(200, {'Content-Type' : mime.lookup(filename) }); res.write(file, "binary"); res.end(); }); }); } } ... </code></pre> <p>This action getfile in the content controller looks for the file specified in the URL in the content directory and serves it up to the client. It <code>requires</code> the mime library that you can get with NPM.</p> <p>This enables the use of static files in the /content/ folder. If you'd like to you could make the route catch every non caught URL and look for a static file from the route up. However you'd have to set up some kind of filter so that you can't just access server.js file.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload