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!”

______________________

White Paper
Linux Management with Red Hat Satellite: Measuring Business Impact and ROI

Linux has become a key foundation for supporting today's rapidly growing IT environments. Linux is being used to deploy business applications and databases, trading on its reputation as a low-cost operating environment. For many IT organizations, Linux is a mainstay for deploying Web servers and has evolved from handling basic file, print, and utility workloads to running mission-critical applications and databases, physically, virtually, and in the cloud. As Linux grows in importance in terms of value to the business, managing Linux environments to high standards of service quality — availability, security, and performance — becomes an essential requirement for business success.

Learn More

Sponsored by Red Hat

White Paper
Private PaaS for the Agile Enterprise

If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.

Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.

Learn More

Sponsored by ActiveState