Skip to content

Simple lightweight node.js web server

The simplest definition of Node.js, defines it as Server Side JavaScript. The more complex definition will most definitely include some reference to Node.js using an event-based server execution procedure making it easier for developers to implement server side event driven architecture in their applications.

One of the very many cool things about node.js, is that it makes it possible to easily create really simple event driven applications with very few lines of code.

In this post I will walk you through developing a simple lightweight node.js web server and incorporate some logging, along the way we'll learn some of the basic concepts and features of the Node.JS and JavaScript.

I'll be using my favourite Javascript IDE, Webstorm  , to do this but you can easily follow along using a text editor and the command line.

You'll also need to ensure you have node installed on your machine, Check out my post for instructions on how to install node.js on ubuntu desktop.

Getting Started

If you understand the basics of Node.js, you'll know that Node.js has a simple module loading system. In Node.js, files and modules are in one-to-one correspondence and each file is treated as a separate module).

One of these Node.js modules is the http module which helps to manipulate and handle the HTTP request and response . http messages.

For a detailed discussion about this API check out Node.js v8.2.0 Documentation.

We'll make use of the http module for our little application.  So in order to do so we need to create a new blank JavaScript file can call it webserver.js  paste the following code in.

var http = require('http');
var server = http.createServer(function (req, res) {
    var body = 'Amazing lightweight webserver using node.js\n';
    var content_length = body.length;
    res.writeHead(200, {
        'Content-Length': content_length,
        'Content-Type': 'text/plain' });
 
    res.end(body);
});
server.listen(3939);
console.log('Server is running on port 3939');

As you can see there is not a lot of code to write to create this little web server.  All we've done here is referenced the http module  created a server and set it to listen on port 3939.

In order to run the webserver just go to your command line and invoke it with the following

node webserver.js

Once you have executed the command you computer will now have a web server running on port 3939. You can test this web server using two methods.

The first method is to open a web browser i.e. Google Chrome, Safari or Firefox etc. and navigate to  to http://localhost:3939

node.js web server

You'll notice the little web server responds and  the web page is displayed.

The second method you can test is by using a command-line program curl, which most Mac and Linux machines have pre-installed. Open a terminal window and type

curl -i http://localhost:3939

You should now see something similar to the following

HTTP/1.1 200 OK
Content-Length: 44
Content-Type: text/plain
Date: Sun, 28 Feb 2016 21:44:21 GMT
Connection: keep-alive
 
Amazing lightweight webserver using node.js

As you can see we've created a pretty cool a web server in just 9 lines of code! Obviously it doesn't pack all the features of Apache etc, but it still is a handy little web server. At the moment it only has one route and you can't really do anything else with it, but from this point on we can scale it a bit more.

Node.js provides a lot of powerful functionality out of the box, and as we can see in the first line of the previous code, you can use one of the built-in modules - the http module, which allows your app as a web server.  The require function includes this function and we created a variable of http to refer to it.

The createServer function takes only one argument, a function that will be called whenever somebody makes a connection to your server. You will typically pass a ServerRequest and a ServerResponse objects to the function. Once the server is created, you tell it to start listening for requests on a particular port - in our case we used 3939 - when you launch the program.

To stop the web server,  go back to the command line and CTRL + C

Lets now make it a little more complicated and enable it to handle a few more routes and create a log entry if somebody tries to browse to a route it doesn't know about. We are now going to start diving into some basic features that make node so extensible. We start using the Node Package Manager (NPM)

What is NPM ?

A detailed discussion of NPM is beyond the scope of this post, but I recommend you visit the great tutorials at https://docs.npmjs.com/getting-started/what-is-npm   or watch this short video will give you most of the information you'll need.

https://youtu.be/x03fjb2VlGY

A logging web server

In order to create a logging web server we are going to use an existing library within NPM called log4js.  First we'll need to configure our application to use npm  and import the log4js module. To do this we'll go to the terminal window and navigate to the directory that contains our JavaScript files and execute the command.

npm init

We'll answer all the questions, don't worry too much about what all these mean right now, and we will be able to edit the answers we provide later.  Once the command has finished executing you will notice a new file and a new directory appear in your directory.

  • package.json
  • node_modules

I'll explain more about these files in a later tutorial but for now feel free to explore the file and directory. You'll see the file will contain all the answers to the questions you answered during the previous step.

The next step will be to import the log4js file into your project. To do this we will execute another line in the terminal window.

npm install log4js --save-dev

We'll need to create a new directory in our project folder , and call it logs.  

Create a new JavaScript file and call loggingwebserver.js

We'll also need to create a reference to log4js module and configure it to create an error log file. We'll also add a basic switch statement to handle a few basic routes, with a default which handles a basic 404 error. The completed code looks like this.

var http = require('http');
var log4js = require('log4js');
log4js.configure({
    appenders:[
        {type:'console'},
        {type:'file', filename:'logs/error.log', category:'webserver'}
 
    ]
});
var logger = log4js.getLogger('webserver');
 
var server = http.createServer(function(req,res){
    logger.info(req.url);
 
    switch(req.url){
        case '/':
            res.write('Welcome to http node.js');
            break;
        case '/about':
            res.write('About us page');
          break;
        case '/contact':
            res.write('Contact us page');
            break;
 
        default:
            var routeNotFound = 'The following route was not found ';
            res.write('404 PAGE NOT FOUND');
            logger.error(routeNotFound.concat(req.url));
    }
    res.end();
});
 
server.listen(3939);
console.log('Server is running on port 3939');

Now if we run the application,  the same as before we start and navigate to the website, we'll start seeing a bit more output on the command line and if you navigate to the logs folder you'll notice a log file created with some entries. Try accessing some of the routes and try entering a route that doesn't exist.

node.js web server with logging

The log file will also have similar entries appended

[2014-11-26 12:17:49.424] [INFO] webserver - /
[2014-11-26 12:17:58.339] [INFO] webserver - /about
[2014-11-26 12:18:06.460] [INFO] webserver - /contact
[2014-11-26 12:18:16.802] [INFO] webserver - /error
[2014-11-26 12:18:16.803] [ERROR] webserver - The following route was not found /error

I'd admit this particular webserver is lacking some enterprise scale functionality, but at its root it is still a webserver and it can be used as a starting point for building a more complex little tool.

As you can see by this short example, that node is extremely scalable and by simply adding a reference to an existing module within the node package manager we can very quickly add and use other libraries to further expand on our existing application.

Summary

Node.JS enables developers to turn any server into a lightweight webserver with just a few lines of code. It's perfect for developing small lightweight event driven web applications, without having to concerns ourselves with all the infrastructure plumbing required.

Gary Woodfine
Latest posts by Gary Woodfine (see all)