Getting started with Node.js


Get a server.

The following was done on a Rackspace CloudServer with a bare bones install of Red Hat Enterprise Linux Server release 6.4 (Santiago).

Install Node.js from binary distribution:

cd /usr/local/
sudo tar xzvf ~/node-v0.8.22-linux-x64.tar.gz --strip=1

Install Forever, which will keep our server alive:

sudo npm install -g forever

Install node-static, a recommended RFC2616 compliant (HTTP 1.1) static file server:

sudo npm install -g node-static
sudo npm link node-static

Redirect port 80 traffic to a port we can listen to without running our server as root:

sudo iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080
sudo service iptables save

Create our server, public_html.js, to serve files in the public_html folder:

var http = require('http'),
    static = require('node-static');

// Create a node-static server instance to serve the './public_html' folder
var staticServer = new(static.Server)('./public_html');

http.createServer(function(request, response)
    request.addListener('end', function()
        staticServer.serve(request, response);

And run it forever. This is your production server.

forever start public_html.js

For a development server which restarts when the file is changed, use nodemon.

sudo npm install -g nodemon
nodemon dev_html.js