Saturday, 28 May 2011

Serving static and dynamic content with Node.js and node-static

With a little bit of help from Nodejitsu and Ben Nadel here's a simple js file for serving static and dynamic content. Static content must be in the /s/ directory, which makes it perfect for serving images or css. Note I am listening on 0.0.0.0 to allow external connections. During development you may want to restrict it to 127.0.0.1.
var sys = require('sys');
var http = require('http');
var nodestatic = require('node-static');

var staticServer = new nodestatic.Server(".");

var server = http.createServer(
function (req, res)
{
var url = require('url').parse(req.url);

var pathfile = url.pathname;

sys.puts('request: ' + pathfile);

if (pathfile.search(/^\/s\//) == 0)
{
staticServer.serve(req, res)
}
else
{
res.writeHead(200, { "Content-type": "text/html" } );
res.end('Hello world');
}
}
);

server.listen(8080, '0.0.0.0');

sys.puts('listening..');

0 comments:

Post a Comment