Introduction to Node.js: Part 1

Jon Price - The C2 Group

The C2 Group

Have you ever wanted to write a web application that was 99% JavaScript? I have, and I did. One of our clients required us to create a custom web application that was fast, reliable, and near real time. After looking at a few different solutions, we settled on Node.js to meet their needs. Over the course of my next few blog posts, we will look at Node.js and create a simple web application.

What Is Node.js?

Node.js is a JavaScript runtime that allows you to execute JavaScript code on your computer. Node.js has many applications, but one thing it is really great at is creating scalable, real-time web applications.

You can install Node.js for your platform by visiting http://nodejs.org. Installation is simple and when you are done you will have a node command shell (node) installed as well as the node package manager (npm).

Getting Your Feet Wet

Start up the node command shell and you will be at an interactive command prompt. This prompt is a read-eval-print-loop (REPL). This is where you can execute raw JavaScript code.

> console.log("Shall we play a game?");
Shall we play a game?
undefined
>

Above, I entered the JavaScript command to print out the words “Shall we play a game?”. Node responded with statement, as well as undefined.

I typically do not use the node command prompt. You can also store your JavaScript in files and use node to run them directly. I have created a file named loop-and-print.js that has the following code in it:

for(var i=0;i<=3;i++) {
    console.log(i);
}

And when run, this is the obvious result:

>node loop-and-print.js
0
1
2
3

>

Wading A Little Deeper

I know what you are thinking, ‘That is cool and all, but it’s hardly a web application’. You are right! Let’s demonstrate something more useful. Node by itself doesn’t do anything right out of the box. But it does come with a set of modules you can use to build up an application. Using a couple of these modules and roughly 15 lines of code, we can create a basic web server.

Here is server.js:

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

http.createServer(function (req, res) {
    var reqFile = path.basename(req.url) || 'index.html';
    res.writeHead(200, {'Content-Type': 'text/html'});

    fs.readFile(reqFile, function(err, contents) {
        if(!err)
            res.end(contents);
    });
}).listen(8080);

console.log("Server is running at http://localhost:8080/");

In this application we are using Node’s http, fs, and path modules and have created an http server that listens on port 8080. Next we look up the requested file (in the same directory as server.js) and if the file is found, we send the html back to the client.

In order to use this, you will need to create some basic html files in the same directory as server.js. Then you can open a new browser window and browse to http://localhost:8080/<your_file>.html.

This is a very basic server with limited error checking, no error handling, and limited functionality. You could spend the time building it out further (and I recommend that you try), but in my next blog we will look at a node package that takes care of all of this for you.

Continue on and read Introduction to Node.js: Part 2