Getting Started with Node.js
Written by Mike James   
Monday, 28 November 2011
Article Index
Getting Started with Node.js
Event driven UI

By bringing JavaScript to the server, Node.js is something of a buzz in the wider JavaScript world. Here we look at the problem it solves and how to make good use of it.

Why bother having one language for the client and one for the server? Why do I have to write code in the web page in JavaScript but when I move to the server I have to switch to PHP or something else? There are some situations in which a polyglot approach to programming makes sense but using one language on the server and one on the client simply makes things difficult for no real reason. If you write an Ajax request in the client why do you then have to switch to PHP to create the response?

It doesn't make sense and the reasons for it are more a matter of history than any logic.

Node.js is JavaScript on the server but it doesn't achieve this by simply grafting a language onto the existing web server like PHP or .NET - instead the web server is built into the Node.js system. That is, you install Node.js and you have a ready-to-run web server.

There are also some other facts about Node.js that are worth knowing, in particular that it implements an event-oriented way of organizing the server, but these can wait until you have found out a little more about how it all works.


First you need to download and install Node.js. Although there are instructions on the Node.js site they fail to explain how easy it is. So for once the purpose of this getting started step is to tell you that it really is easy to install Node.js and this is one of the reasons there aren't any long lists of instructions on how to do it.

First you need to download a binary. You can download the source and compile it if you want to but in nearly all cases there isn't any need to do so.

If you are running Linux of any description, follow the instructions about installing using a package manager.

If you are running Windows or Mac then simply use the installer you will find at Download.

Before the latest version of Node.js it was more difficult to get it working under Windows but now you can simply use the installer and expect it to all work without you haven't to install anything else first.

From this point on I'm going to be describing how the Windows version works but the other installations work in more or less the same way with slight changes in directories where the files are stored etc.

A simpler Hello World

After installing Node.js the actual server and other executables are stored in Program Files/nodejs, but you don't have to make use of this information because the installer adds this to your execution path. To write Node.js programs you will need a suitable JavaScript editor - Notepad will do - and a command line shell. It is best to keep both open at the same time.

To get started let's create the simplest program possible, and it is much simpler than the Hello World you will find in the documentation:

console.log('Hello NodeJS World');

Enter the above line of JavaScript and save the file as Hello.js.

Next open a command prompt and change the current directory to the one you saved Hello.js in - you should be able to see it when you type Dir. Finally enter the command:

node hello

You will see

Hello NodeJS World

printed on the next line. If you don't see the message then you need to check that Node.js was installed and that the files are all where you thought you stored them.

Just in case you accidentally type in just NodeJS it is worth saying that this starts a shell that you can use to type in JavaScript and execute it in immediate mode. To exit this shell simply type Ctrl-C twice. For more information on how to use the shell, look up REPL in the documentation.

The Server

The program has successfully printed a single line of text to the console. This may not be a very inspiring start but it is an example of JavaScript running out side of the browser and you can now start to write applications that access the file system on the local machine, do database lookup and so on.

However this isn't really what Node.js is all about.

The idea is that you write JavaScript to serve data to a client web browser. You can do this in a number of ways but the simplest is to start a web server.

First you need to create a web server and this requires the JavaScript module that defines it:

var http = require('http');

The require function loads the module if it hasn't already been loaded and returns an object which provides its functionality.

Now we have an http object that has a set of methods, events and properties that let us work with HTTP requests. Its most important method is createServer which creates a server object that can be set to listen on any IP address port combination and when it gets a request it will run a function that you specify. You can define the response function anyway that you like but for such a simple example it might as well be defined in the call to createServer:

var webServer=http.createServer(
function (req, res) {
res.writeHead(200, {
'Content-Type': 'text/plain'});
res.end('Hello World\n');

The response function accepts two parameters:

  • The req parameter is an object that represents all of the information about the request - e.g. the URL, the headers and so on.
  • The res parameter is a writable stream that is used to send the response back to the client.
In this case all that happens is that we write a minimal HTTP header and a single text line saying "Hello World".

Finally to make the server active we use its listen method:

webServer.listen(1337, "");
console.log('Server running at');

The listen method in this case assigns port 1337 to the server and we print a console message that acts as a reminder of this.

To see the program in action simply start up a browser and enter the URL and you should see the hello world message.


Last Updated ( Monday, 28 November 2011 )

RSS feed of all content
I Programmer - full contents
Copyright © 2014 All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License.