In association with heise online

A simple Node.js Server

As an example of Node.js code, here's a slightly over-engineered "Hello World" program which reads who it's saying hello to from a file in /tmp:

    var http = require('http');
var fs = require('fs');
    http.createServer(function(req, res) {
fs.readFile("/tmp/hellomsg.txt", function(error, text) {
res.writeHead(200, {'Content-Type': 'text/plain'});
if (error) {
res.end('Not ready to say hello...\n');
}
else
{
res.end('Hello '+text+'\n');
}
});
}).listen(1337, "127.0.0.1");
    console.log('Server running at http://127.0.0.1:1337/');

A line by line examination will shed some more light on this.

    var http = require('http');
var fs = require('fs');

JavaScript lacks any built-in packaging system for modules, so Node.js uses Common.js conventions for handling libraries. The require function will retrieve the library and return a handle to it; var http= saves that value in "http". Then we repeat the process for "fs", the file system library. The handles can be used to call functions within the libraries, which is what happens next...

    http.createServer(function (req, res) {

There's a lot going on here. The http library is being asked to create an HTTP server. When there is any kind of request on the server, it will call the defined function. Notice that objects can be passed to the function: here a req object will contain information about the request made and the res object can be filled in with the program's response to the request.

But first we need to get the text of who we want to say hello to...

    fs.readFile("/tmp/hellomsg.txt", function(error, text) {

The fs.readFile function takes a filename to read and when it has read the file it calls the callback function that we're about to specify. That callback function gets passed two values, whether an error occurred, and if not, the contents of the file. Before we go on, we keep things simple and begin building up the response. The res object also has functions to assist building up the response:

    res.writeHead(200, {'Content-Type': 'text/plain'});

Here, the header of the response is being written. The HTTP status 200 is being added, along with a media description of the content, yet to be added, as plain text. Now the next step should be to write something into the content of the response and send the response back to the server to be despatched onwards...

      if (error) {
res.end('Not ready to say hello...\n');
}
else
{
res.end('Hello '+text+'\n');
}

The res.end function is a bit of practical shorthand from the http library; this could be written as

    res.write('Hello '+text+'\n');
res.end();

But res.end was extended to make it easier for responses where the one string contained the response by allowing it to be passed in the end statement. The res.end function also sends a signal to the server that the response is complete and ready to be sent.

        });
}).listen(1337, "127.0.0.1");

With the function defined, the listen function of the created http server can now be invoked to tell it where to listen...

    console.log('Server running at http://127.0.0.1:1337/');

And a message can be emitted on the console to show that we are running. So there we have a very simple HTTP server. It waits for a connection and, if there is a connection, wakes up and calls our function. Our function asks to read a file and instead of stalling, waiting for the file to be opened, read and closed, it asks for a function to be called when it's done. It is that function that assembled the "Hello" response with the read text and packs the response back off to the server.

Next: Node.js Resources

Print Version | Permalink: http://h-online.com/-1612908
  • Twitter
  • Facebook
  • submit to slashdot
  • StumbleUpon
  • submit to reddit
 


  • July's Community Calendar





The H Open

The H Security

The H Developer

The H Internet Toolkit