Node.JS
AJAX is a useful technology for web applications that need to pull periodic updates from your server. But what do you do when you have thousands of clients all requesting data that changes real-time? A PHP+AJAX approach would choke. It is situations like these that Node.JS comes to the rescue.
Contents
A Review of Non-Blocking I/O
You dabbled in the concept of non-blocking I/O when you implemented AJAX in the previous JavaScript module. Node.JS uses this execution model at its core.
The core idea is the use of anonymous functions as callbacks for processing the results of intensive operations. Consider the pseudo-code:
// Blocking I/O Pseudo-Code
var data = database.query("select * from news");
print data[0].title;
The above pseudo-code queries a database, saves the result of the query in a variable named data, and then prints out the first title in data. The problem arises when multiple clients all want to access the server at the same time. In a blocking I/O model, a client needs to wait until all other clients are finished before it can start its process. With intensive operations and thousands of clients, this can easily crash your server!
The solution is to use non-blocking I/O. Consider this revised pseudo-code:
// Non-Blocking I/O Pseudo-Code
database.query("select * from news", function(data){
print data[0].title;
});
The revised pseudo-code achieves the same end result as the first version. However, it allows other clients to perform tasks while this process is waiting for the database to be queried! The code occurs in two parts: first, we start the query. Second, when the query is complete, our anonymous callback function is executed. In Node.JS, callback functions are usually passed one or more parameters.
Better yet, with non-blocking I/O, you have no concurrency issues, because everything runs in just one thread. Nifty!
Installing Node.JS
Debian
Installing Node.JS is as easy as installing some packages from the Apt repository.
$ sudo apt-get install python nodejs npm nodejs-dev
Make sure you have build-essentials installed as well. (You should have done this when you first made your instance.)
RHEL
For whatever reason, you can't currently install an updated version of Node.JS from Yum. You will therefore need to compile it from source.
Get the link to the most recent version of the Node.JS Linux binary from http://nodejs.org/download/ (you can use the 64-bit version).
Download, unpack, configure, and make the package. For example:
$ cd # go to your home directory
$ wget http://nodejs.org/dist/x.x.x/node-x.x.x-linux-x64.tar.gz # download the tarball (remember to change the path)
$ tar -zxf node-x.x.x-linux-x64.tar.gz # unpack the tarball
$ cd node-x.x.x-linux-x64
$ ./configure
$ make
$ sudo make install