Building a Basic Web Server in Node.js

Node.js is a runtime that can be used to execute javascript code outside of the browser. I have been wanting to look into it for a while now and especially it's place in the MEAN stack (a web stack that is entirely javascript based).

I have the book, Node.js for PHP Developers, by Daniel Howard, which is designed to help PHP developers, like myself, get to grips with Node.js by translating the concepts from one language to the next.

In the post, I will go over the very basic "Hello, World" web server example.


As a Windows user, I often have difficulty setting up development environments and usually resort to using an Ubuntu VM. But in this case, it is actually very easy.

If you go to the website, you can find an installer that will set everything up.

You can then, in command prompt, run the command npm or node without any further issues!

Node.js Server

Unlike PHP, node.js doesn't run on a web server. If you want to use it for a web system, then you must build a web server using it!

The following is boiler-plate code for a very basic node.js server:

var http = require('http');

http.createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World!\n');
}).listen(1337, '');
console.log('Server running at');

So what is it doing?

The first line demonstrates one of the biggest strengths of node.js: the availability and ease of loading of pre-existing modules. In this case, we are loading the module, http, which will provide the functionality that we need.

Next, we use the createServer function from the http module. This accepts a function as it's parameters that is the web server itself. This function accepts two parameters: request and response.

Inside this function, we do two things: we give the response object a header which gives it a 200 OK status and that the content we are returning is plain text. We then give the content, which is a hard coded string. So, anyone who hits this server will be given a plain text string: "Hello World!" and a 200 OK HTTP status.

The function, createServer then returns the server object with our functionality installed. On the last line, you can see that I call the listen function which tells the server to listen to requests coming to "".

Finally, I have a console log just to show that we got there.

So, if I run this using note ws.js (where ws.js is the name of the file with the above code):

You can see that it prints the log, but also the process doesn't end as the server is now running.

I can then hit the address "" in my favourite web browser and I see:

A working response.


Obviously this is a very simplistic example of a node.js web server and a very simple use for node.js as a language. But it is a great start to get experimenting with! Good luck!

© 2012-2017