Javascript on the server side

For the last decade javascript has been a language that has almost exclusively been run on the client side, in the web browser. But during the past year it seems like Javascript has found its way to the server side as well, to the joy of some developers while others wrinkle their nose and wonders why you would ever use Javascript for something more advanced than client side processing.

The fact is that Javascript is a very powerful language, unfortunately it has had a bad reputation for many years. I admit, for a long time I also looked at JavaScript as a second-class citizen in the programming world. A programming language used only to glue together HTML pages, while the heavy lifting was done on the server side in C#, Java, Ruby or in any other “real” language. However, my view of Javascript has drastically changed during the last few years. The language have “grown up”, and by that I don’t really mean the language itself, instead I am thinking about the libraries and tools available for Javascript, such as jQuery, JSON, Node.js, and HTML5. jQuery was a major game changer on the client side and now we have Node on the server side.

Node is a low level framework for building high performance web applications. It contains of an interpreter based on Google’s V8 and a framework library. HTTP is a first class protocol in Node and it is very easy to get a web server up running. The main difference from traditional frameworks is that Node is event driven (asynchronous). While most webservers use synchronous thread pool based request handling, Node server will only run one event loop which will handle all incoming requests using callbacks. Asynchronus web servers are proved to be very fast, for example the Nginx and Lighthttpd web servers, and Node is not an exception.

Let me show you what the simplest web server in Node looks like:

var http = require("http");

http.createServer(function(request, response) {
  response.writeHead(200, {"Content-Type": "text/html"});
  response.write("Hello World!");
  response.end();
}).listen(1234);

Running the program will start a web server listening on port 1234 and visiting http://localhost:1234 will show a “Hellow World!” message to the visitor.

The main difference when writing code for Node is that you have to understand is that blocking IO should be avoided. Everything runs in parallell except your code, writing blocking code will prevent Node from serving other requests. This is an example of writing blocking code:

var http = require("http");
var url = require("url");

http.createServer(function(request, response) {
    response.writeHead(200, {"Content-Type": "text/html"});
    var pathName = url.parse(request.url).pathname;

    if (pathName == "/longrun"){

        function sleep(milliSeconds) {
            var startTime = new Date().getTime(); // get the current time
            while (new Date().getTime() < startTime + milliSeconds); // hog cpu
        }

        sleep(10000);
        response.write("Long run...");
        response.end();
    }
    else
    {
        response.write("Hello World!");
        response.end();
    }

    
}).listen(1234);

The above example listens to two urls http://localhost:1234 and http://localhost:1234/longrun. When first visiting / it loads fast. Loading the /longrun takes 10 seconds as expected (think of this as database query or some other IO operation that takes long time), but it also causes Node to block and not serve new requests until /longrun has completed. To avoid this you should use non blocking IO at all times. By doing this, Node will be able to process other requests while waiting for the request to complete.

For a more in depth introduction to Node I can recommend the short book "The Node Beginner Book" and also the blog post "Understanding the node.js event loop"

To get started with Node I suggest you head over to Github and follow the intallation instructions to install Node and npm (the package manager for Node) https://github.com/joyent/node/wiki/Installation.

Peter

3 thoughts on “Javascript on the server side

  1. It seems cool, but does it scale well?

    I would use another language for the server-side just to get a break from all the javascripting that we have to do on the client’s end of things.

    Did you use it in production?

  2. I started playing around with Node.js just a few weeks ago, so I haven’t had time to use it in a real world application yet. But from what I have read and heard from people I know use it, it seems like Node scales _really_ well. And in the future it will hopefully perform even better by providing multicore support by using the Web Workers API (when it is approved and implemented in V8)

    One of many microbenchmarks I have found:
    http://www.synchrosinteractive.com/blog/9-nodejs/22-nodejs-has-a-bright-future

    One scenario where it Node really suited is when you build a comet (long running http connections) server/client application, or any application that needs to keep a lot of http connections open. On Apache or IIS, that uses a thread pool to process requests, each client would be processed in a thread and once the number of clients connected reached the max limit of the thread pool, the server would no longer be able to process incoming requests. Of course there are workarounds for this, but with Node no additional work would be needed, it would work out of the box.

Leave a Reply

Your email address will not be published. Required fields are marked *