Pages

Tuesday, October 16, 2012

Minimalist Web Server

As modern browsers are restricting access from HTML pages to local files, it is becoming necessary to serve them from a web server. For this purpose it is an overkill to install or even just set up a site in Apache or IIS. In the past I've used Tiny Web Server (link) but nowadays there are better options.
Currently, my preferred option is using Node.js with node-static (link).
See the code below or click here to see it on Github.Gist.

var static = require('node-static');
//
// Create a node-static server instance to serve the current folder
//
var file = new(static.Server)(__dirname);
require('http').createServer(function (request, response) {
request.addListener('end', function () {
//
// Serve files!
//
file.serve(request, response);
});
}).listen(8080);
This requires node-static to be installed. The most convenient way is to add it as a dependency to the package.json, like this:
{
"name": "minimal-web-server",
"version": "1.0.0",
"dependencies" : {
"node-static" : "*"
}
}
view raw package.json hosted with ❤ by GitHub
and run "npm install".
Then, simply add index.html or other static files and the server is up and running.

No comments: