Creating the webserver

The first thing to remember – and a big change to get used to if you’re coming over from a Microsoft IIS stack, or an Apache based stack – is that with Node.js there is no webserver until you create it. And that’s what our first two lines are doing.

Calling the HTTP module

Starting at the top, the very first thing we do is load in the pre-prepared HTTP module that ships as part of node. You’ll see this type of syntax a lot, as Node.js programming uses a lot of modules. As a best practice it’s a good idea to set the variable name to match the module name.

var http = require('http');

Create the server

Stripping out the callback function to make it a little more clear, we can look at the createServer method of HTTP like this:

http.createServer(function(req, res){ }).listen(8888, '127.0.0.1');

What we are doing here is creating a HTTP server to listen to requests (req) made to port 8888 on the IP address 127.0.0.1, and also send response objects (res) back to the same IP and port. The IP address 127.0.0.1 is common across many OS’s as the ‘localhost’ server.

We also output a message to the console to show that we’ve reached the end of the script and that the server is running:

console.log('Server running at http://127.0.0.1:8888');

But what about the middle bit?!

Okay, so in a nutshell what we’re doing here is responding to any request in exactly the same way. Let’s break that response down.

res.writeHead()

The first part of the response object is another item that you’re probably not used to really thinking about if you’re coming from a traditional stack where the web-server does all this for you. We need to send the HTTP headers. Here we’re just sending the HTTP status code and content type. So to say that the request was successful, and that we’re sending back HTML content we type:

res.writeHead(200, {'Content-Type': 'text/html'});

res.write()

Next we want to send some content back to the response object. Here we’re doing it all as one long string: