Portable Web Server

Posted by Simeon on Jul 6, 2011 in Blog | 1 comment

I have been meaning to write about this for a while, but I just keep not finding time. But tonight I was reading through the Sammy JS Tutorial, and I decided that I needed to make time. I have been spending a lot of time with Node.js lately. I have even given a couple presentations. While there are many things that Node.js does, one of the most practical purposes is as an on-demand web server.

Using Connect static provider module with Node.js its trivial to create a web server that can serve static files from a local directory. This has several advantages of allowing you to execute your content using http:// instead of the file:// url. For single page javascript applications this means chrome will correctly execute your AJAX calls. For Flash applications this means you can serve your bin-debug directory and have your swf’s execute in the correct security context.

The short version of this long story is that with this very simple bit of code you can have a web server running on the port of your choice. Requirements for this to work are to have Node.js installed, as well as NPM. Use NPM to install connect, and then save the code below as app.js.

var connect = require('connect');
var server = connect.createServer(
    connect.static(__dirname + '/public')
);
server.listen(8080);

Then from the command line run the following command from the directory where you saved the javascript file.

node app.js

You wont see any output on the command line, but you will have a web server running on port 8080 serving whatever files you put in the public directory which is relative to the app.js file. Just fire up your favorite browser and navigate to http://localhost:8080/ which will try to load the index.html file from that public directory.

You can only run one process on a port at any given time, but you can copy that file around and use it in several places if you change the ports.

One Response to “Portable Web Server”

  1. That is very cool! I’m glad to get some input from someone who seems experienced. With the technology that we have nowadays, it seems that anything is possible… well, with the right equipment anyway :) Thanks!

Leave a Reply