Node.js for hosting websites

Flattr the Node.js for hosting websites post

Whilst Node.js is primarily aimed at creating non-blocking servers it can also be used to host simple web pages such as homepages and blogs.

We are going to be using a simple web framework for Node.js called Express (http://expressjs.com), which can be installed via the Node Package Manager on the command line.

npm install express

Firstly, create a new file called server.js and begin by instantiating the express framework.

var app = require('express').createServer();

The server now needs a web route to dispatch, so define the URL and pass in a callback function to handle the request.

app.get('/hello/:name', function(request, response){
    response.send('Hello ' + request.params.name);
});

See how :name in the route becomes a variable you can access in the request parameters and is used in the response text from the server.

Finally from the server point of view you need to define a port number to listen to incoming requests on.

app.listen(3000);

If you now run node server.js on the command line and navigate to http://localhost:3000/hello/Test in your web browser you will see the page you just created. Try swapping Test for your name in the URL and refresh the browser.

Now you are able to create simple pages with the Express framework and Node.js. For further experimentation you could take a look at using Jade (jade-lang.com) as a template engine and making use of static routes to serve images and CSS files.

If you like this article then you will probably also be interested in Getting started with Node.js and CouchDB and Nodester environment variables for sensitive data and passwords.

Note

This article was originally published in the April 2012 issue of .net Magazine.

The accompanying tutorial to create a Google Talk bot with Node.js is also published on my blog.

In tandem with the Google bot tutorial I wrote four smaller articles: