At the Forge - Node.JS

Want to write high-performance network server applications? Node.JS uses JavaScript to do exactly that.
npm and More Advanced Programs

What, you're not impressed by a high-speed “hello, world” program? I can understand if you're hesitating. And besides, the last few years have shown how powerful it can be to have a high-level abstraction layer for creating Web applications. Perhaps if you were writing low-level socket programs, it wouldn't be a problem for you to send each header and the contents. But maybe there's a way to have the high speed of Node.JS, while enjoying a high-level Web development library. Or, perhaps you're interested in building not a Web application, but something that'll be appropriate for a newer protocol, such as Web Sockets.

I've already shown that Node.JS supports the CommonJS standard for external modules, such that you can require a file and have its contents imported into a local variable. In order to promote the distribution and usage of many such modules, Isaac Schlueter created npm, the Node.JS package manager. npm doesn't come with Node.JS, but I expect this will change over time.

To install npm, simply run the following command (but not as root!) from the shell:

curl http://npmjs.org/install.sh | sh

If you find you cannot install it because of the permissions associated with the node.js directory, you should not install npm as root. Rather, you should change the permissions on the node.js directory (typically /usr/local/nodejs), such that you can install npm as a regular user.

Once you've installed npm, you can get a list of what's available with npm list. This lists all the packages, and at the time of this writing, there were more than 3,700 packages available, although I must admit that each version of a package counts toward the list.

To install one of these packages, simply type:

node install express

And sure enough, the npm module “express” is installed. I should add that it took me a while to get the permissions right, such that npm could install things into /usr/local on my server to which a nonroot user typically has limited rights. I hope these sorts of permission issues will go away in the future, perhaps by putting npm's files in a place other than /usr/local.

Now that you have installed this module, what do you do with it? You can write a simple Web application for starters. Express is designed to be much like Sinatra, a simple Web server for Ruby. Here's a simple “Hello, world” program in express, based on the express documentation:

var app = require('express').createServer();

app.get('/', function(req, res){
    res.send("Hello, world\n");
});

app.listen(3000);

In other words, you first require the express module. Because you downloaded express via npm, it is available to you automatically. You don't need to set any paths or options. You then get the result back from loading the module and immediately create a server, which you put into your app variable. app is what you will use throughout your application.

Then, you tell the application that when it receives a GET request for the '/' path, it should execute the function that you indicate. Notice that you don't have to deal with the low-level details of HTTP responses here. You simply can send your response and be done with it.

You then tell the application to listen on port 3000. You can save and run your application, and when you go to /, you get your greeting.

Well, what else can you do? I've expanded express.js a bit and put it into Listing 1. To begin with, you can see that by specifying a Rails-style route (/person/:id) with a colon in front of one of the path segments, you can set a parameter name that is retrieved automatically, and that is then available via app.params.id:

app.get('/person/:id', function(req, res){
    res.send('Oh, you want information about person ' 
    ↪+ req.params.id + "\n");
});

Going to /person/100 will result in the output:

Oh, you want information about person 100

which means that the parameter can be used as the key in a database, for example. (And if you wonder whether Node.JS can talk to a database, be aware that there are adapters for many of them—both relational databases, such as MySQL and PostgreSQL, and also non-relational databases, such as MongoDB, Redis and CouchDB.)

You aren't limited to GET requests:

app.post('/foo', function(req, res){
    res.send("You requested foo\n");
});

If you ask for /foo via a POST request, you will get this response. But if you ask for /foo via GET, you will receive a 404 error from Node.JS.

Finally, you also can use templates on the filesystem. One particularly Ruby-style template is called ejs, and it has a virtually identical syntax to Ruby's ERb (embedded Ruby), including the need for a “views” directory and for a layout. Create a views subdirectory, and put index.ejs in it, as per Listing 2. You then can do something like the following:

app.get('/file/:id', function(req, res) {
    res.render('index.ejs', {
      locals: {param: req.params.id}
    })});

Here, you're taking the parameter (which you're calling id), and you're passing it to your template (index.ejs) as the local name param. You then ask express to render your template with the variable in it. Sure enough, your template is rendered in all of its HTML glory, with the data that you passed to it.

______________________

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