Thursday, February 2, 2012

node-static for Serving Static Files with Node.js

node-static can be installed via npm with the following command:
npm install node-static
To use it: include the module in your script via the require function, create a server, pass it your preferred options, and tell it to serve files:
var static = require('node-static'),
  http = require('http'),
  util = require('util');
var webroot = './public',
  port = 8181;
var file = new(static.Server)(webroot, {
  cache: 900,
  headers: { 'X-Powered-By': 'node-static' }
});
http.createServer(function(req, res) {
  req.addListener('end', function() {
    file.serve(req, res, function(err, result) {
      if (err) {
        console.error('Error serving %s - %s', req.url, err.message);
        if (err.status === 404 || err.status === 500) {
          file.serveFile(util.format('/%d.html', err.status), err.status, {}, req, res);
        } else {
          res.writeHead(err.status, err.headers);
          res.end();
        }
      } else {
        console.log('%s - %s', req.url, res.message);
      }
    });
  });
}).listen(port);
console.log('node-static running at http://localhost:%d', port);
Here, when we create a new instance of a node-static server, we pass it:
  • the directory we want it to serve files from by way of the `webroot` variable (defaults to serving files from the current directory unless you tell it otherwise)
  • a cache value of 900, so each file served will be cached for 15 minutes (default value for cache is 3600, meaning files are cached for 1 hour)
  • a custom ‘X-Powered-By’ header (I’ve used X-Powered-By solely as an example – you may, or may not, want to disclose the software you’re server is running)
We then use the http module’s createServer function, and add an event handler for the request’s end event where we use our instance of node-static to serve the files.
When we call file.serve, we pass it an optional callback function that let’s us customise how we handle any errors:
  • we check err.status, and serve either 404.html or 500.html accordingly
  • if there’s an error and the status code is something other than 404 or 500, we send the status code and the headers back to the client explicitly – when you pass a callback function to file.serve and there is an error, node-static will not respond to the client by itself.

No comments:

Post a Comment