Simplicity and Performance: JavaScript on the Server

The award for the hottest new server Web development language goes to...JavaScript! JavaScript, language of the browser since the early days, is the hottest language for server-side development. See why JavaScript is the language for developing quick, easy and incredibly powerful server-side applications.
Installing Node

Node will install on almost any platform, but it is ideally suited to UNIX-like environments, such as Linux, UNIX and Mac OS X. It can be installed on Windows, using Cygwin, but it is not as easy as the other platforms and there are plenty of gotchas. Like most server-side packages, if you want to do anything serious, do it on UNIX/Linux/BSD.

On Linux or UNIX, installation follows typical UNIX program installation: download, configure, make, make install.

First, download the latest package. At the time of this writing, the latest unstable version is 0.3.2, and the latest stable is 0.2.5. I recommend moving toward 0.3+ as soon as possible. Don't be fooled by the low version numbers; plenty of production sites are using Node right now for at least part of their environment, including github.com.

You can download the tarball directly from nodejs.org, or clone the github repository, my preferred method. If you don't have git installed already, do so via your preferred package manager or directly. Before you get started, make sure you have the prerequisites. Although I could include them here, the details of building git are beyond the scope of this article.

On Mac OS X:

# install XCode from the Apple developer Web site
$ brew install git

On Linux or similar with the apt packaging system:

$ sudo apt-get install g++ curl libssl-dev apache2-utils
$ sudo apt-get install git-core

Now, you are ready to download, compile and install Node. First, you need to cd to the appropriate directory. At that point, clone the git repository:

$ git clone git://github.com/ry/node.git
# if you have problems with git protocol, http works fine
$ git clone http://github.com/ry/node.git

Next, make sure you are in the right version. Because git clones the entire repository, make sure you switch to the correct version:


$ cd node
$ git checkout <version>
# version can be whichever you want, 
# but I recommend v0.3.2 as of this writing

Then, run configure. As usual, configure will check whether you have all of the prerequisites installed. Configure also will determine where to install Node when it is ready. Unless you are working on a production machine, I highly recommend installing Node in a local writable repository under your home directory, such as ~/local/. Installing git in the default /usr/local/bin/ leads to all sorts of interesting permission issues when installing packages and running everything as sudo during installs. Unless it is going to be shared among everyone and used in production, installation makes a lot more sense in your own directory. It is also quite small. The entire installation on my laptop, including binaries, man pages and several add-on packages, is less than 50MB. The Node binary itself is less than 5MB:

# installing in the default
$ ./configure

# installing in your own local directory, 
# my preferred method
$ ./configure --prefix=~/local

Then, compile and install:

$ make
$ make install

At this point, Node is installed and ready to run. If you installed Node in ~/local/, you need to add ~/local/bin to your path, which depends on your shell.

A New Mindset

The critical thing to remember about Node development is that everything important is asynchronous. Sure, you could do many things synchronously, but why would you?

For example, a traditional Web programming model might look something like this:

// pseudo-code
conn = connection.waitForRequest();
if (conn != null) {
   request = conn.getRequest();
   response = conn.getResponse();
   data = database.getData(query);
   response.write(someData);
}

In asynchronous Node, you would do something more like this:

server.handleRequest(function(request,response) {
   // we need some data from the database
   database.submitQuery(query,function(data) {
      response.write(data);
   });
});

Notice how everything is in callbacks, an event-driven asynchronous model.

Sample Program One: Hello World

Everything starts with hello world. This example demonstrates the basics of modules and asynchronous handling of requests.

First, include the necessary http module:

var http = require('http');

http is a standard module included with Node. If you wanted a module that was not in the standard path, you would preface it with ./, which is executed relative to the path in which the app is running. For example, require("./mymodule");.

Next, create the server, which is as simple as createServer(), as well as the callback function to handle each request:

http.createServer( function(request, response) {
   // handling code here
});

Next, put in the handling code. You know you want the response to be hello world and the http status code to be 200, which is basic success:

http.createServer( function(request, response) {
   // set your status code to 200 and content to plain text, 
   // since "hello, world!" is as plain as it gets
   response.writeHead(200,{"Content-Type": "text/plain"});
   // write out our content
   response.write("Hello, world!\n");
   // indicate that we are done
   response.end();
});

The above is a callback function. It will be called each and every time a new connection request comes in.

Finally, you need to tell the server to listen and on which port. For now, let's put it on 8080 (just to annoy Tomcat):

http.createServer( callbackFunction ).listen(8080);

Pulling it all together, you get a very simple program:

var http = require('http');
http.createServer( function(request, response) {
   // set your status code to 200 and content to plain text, 
   // since "hello, world!" is as plain as it gets
   response.writeHead(200,{"Content-Type": "text/plain"});
   // write out our content
   response.write("Hello, world!\n");
   // indicate that we are done
   response.end();
}).listen(8080);

Six lines of code, and a functioning Web server that says “Hello, world!” Save the file as app.js, and then run it:

# cd to your development directory
$ cd workingdir
$ node ./app.js

Connect your browser to http://localhost:8080, or use curl or wget, and you will see “Hello, world!”

______________________

Webinar
One Click, Universal Protection: Implementing Centralized Security Policies on Linux Systems

As Linux continues to play an ever increasing role in corporate data centers and institutions, ensuring the integrity and protection of these systems must be a priority. With 60% of the world's websites and an increasing share of organization's mission-critical workloads running on Linux, failing to stop malware and other advanced threats on Linux can increasingly impact an organization's reputation and bottom line.

Learn More

Sponsored by Bit9

Webinar
Linux Backup and Recovery Webinar

Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.

In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.

Learn More

Sponsored by Storix