Setting up Node

(For more resources related to this topic, see here.)

System requirements

Node runs on POSIX-like operating systems, the various UNIX derivatives (Solaris, and so on), or workalikes (Linux, Mac OS X, and so on), as well as on Microsoft Windows, thanks to the extensive assistance from Microsoft. Indeed, many of the Node built-in functions are direct corollaries to POSIX system calls. It can run on machines both large and small, including the tiny ARM devices such as the Raspberry Pi microscale embeddable computer for DIY software/hardware projects.

Node is now available via package management systems, limiting the need to compile and install from source.

Installing from source requires having a C compiler (such as GCC), and Python 2.7 (or later). If you plan to use encryption in your networking code you will also need the OpenSSL cryptographic library. The modern UNIX derivatives almost certainly come with these, and Node's configure script (see later when we download and configure the source) will detect their presence. If you should have to install them, Python is available at and OpenSSL is available at

Installing Node using package managers

The preferred method for installing Node, now, is to use the versions available in package managers such as apt-get, or MacPorts. Package managers simplify your life by helping to maintain the current version of the software on your computer and ensuring to update dependent packages as necessary, all by typing a simple command such as apt-get update. Let's go over this first.

Installing on Mac OS X with MacPorts

The MacPorts project ( has for years been packaging a long list of open source software packages for Mac OS X, and they have packaged Node. After you have installed MacPorts using the installer on their website, installing Node is pretty much this simple:

$ sudo port search nodejs nodejs @0.10.6 (devel, net) Evented I/O for V8 JavaScript nodejs-devel @0.11.2 (devel, net) Evented I/O for V8 JavaScript Found 2 ports. -- npm @1.2.21 (devel) node package manager $ sudo port install nodejs npm .. long log of downloading and installing prerequisites and Node

Installing on Mac OS X with Homebrew

Homebrew is another open source software package manager for Mac OS X, which some say is the perfect replacement for MacPorts. It is available through their home page at After installing Homebrew using the instructions on their website, using it to install Node is as simple as this:

$ brew search node leafnode node $ brew install node ==> Downloading ##################################
###################################### 100.0%
==> ./configure –prefix=/usr/local/Cellar/node/0.10.7 ==> make install ==> Caveats Homebrew installed npm. We recommend prepending the following path to your PATH environment variable to have npm-installed binaries picked up: /usr/local/share/npm/bin ==> Summary /usr/local/Cellar/node/0.10.7: 870 files, 16M, built in 21.9 minutes

Installing on Linux from package management systems

While it's still premature for Linux distributions or other operating systems to prepackage Node with their OS, that doesn't mean you cannot install it using the package managers. Instructions on the Node wiki currently list packaged versions of Node for Debian, Ubuntu, OpenSUSE, and Arch Linux.


For example, on Debian sid (unstable):

# apt-get update # apt-get install nodejs # Documentation is great.

And on Ubuntu:

# sudo apt-get install python-software-properties # sudo add-apt-repository ppa:chris-lea/node.js # sudo apt-get update # sudo apt-get install nodejs npm

We can expect in due course that the Linux distros and other operating systems will routinely bundle Node into the OS like they do with other languages today.

Installing the Node distribution from

The website offers prebuilt binaries for Windows, Mac OS X, Linux, and Solaris. You simply go to the website, click on the Install button, and run the installer. For systems with package managers, such as the ones we've just discussed, it's preferable to use that installation method. That's because you'll find it easier to stay up-to-date with the latest version. However, on Windows this method may be preferred.

Installing the Node distribution from

For Mac OS X, the installer is a PKG file giving the typical installation process. For Windows, the installer simply takes you through the typical install wizard process.

Installing the Node distribution from

Once finished with the installer, you have a command line tool with which to run Node programs.

The pre-packaged installers are the simplest ways to install Node, for those systems for which they're available.

Installing Node on Windows using Chocolatey Gallery

Chocolatey Gallery is a package management system, built on top of NuGet. Using it requires a Windows machine modern enough to support the Powershell and the .NET Framework 4.0. Once you have Chocolatey Gallery (, installing Node is as simple as this:

C:\> cinst install nodejs

Installing the StrongLoop Node distribution

StrongLoop ( has put together a supported version of Node that is prepackaged with several useful tools. This is a Node distribution in the same sense in which Fedora or Ubuntu are Linux distributions. StrongLoop brings together several useful packages, some of which were written by StrongLoop. StrongLoop tests the packages together, and distributes installable bundles through their website.

The packages in the distribution include Express, Passport, Mongoose, Socket.IO, Engine.IO, Async, and Request. We will use all of those modules in this book.

To install, navigate to the company home page and click on the Products link. They offer downloads of precompiled packages for both RPM and Debian Linux systems, as well as Mac OS X and Windows. Simply download the appropriate bundle for your system.

For the RPM bundle, type the following:

$ sudo rpm -i bundle-file-name

For the Debian bundle, type the following:

$ sudo dpkg -i bundle-file-name

The Windows or Mac bundles are the usual sort of installable packages for each system. Simply double-click on the installer bundle, and follow the instructions in the install wizard.

Once StrongLoop Node is installed, it provides not only the nodeand npmcommands (we'll go over these in a few pages), but also the slnodecommand. That command offers a superset of the npmcommands, such as boilerplate code for modules, web applications, or command-line applications.

Installing from source on POSIX-like systems

Installing the pre-packaged Node distributions is currently the preferred installation method. However, installing Node from source is desirable in a few situations:

  • It could let you optimize the compiler settings as desired
  • It could let you cross-compile, say for an embedded ARM system
  • You might need to keep multiple Node builds for testing
  • You might be working on Node itself

Now that you have the high-level view, let's get our hands dirty mucking around in some build scripts. The general process follows the usual configure, make, and makeinstallroutine that you may already have performed with other open source software packages. If not, don't worry, we'll guide you through the process.

The official installation instructions are in the Node wiki at

Installing prerequisites

As noted a minute ago, there are three prerequisites, a C compiler, Python, and the OpenSSL libraries. The Node installation process checks for their presence and will fail if the C compiler or Python is not present. The specific method of installing these is dependent on your operating system.

These commands will check for their presence:

$ cc --version i686-apple-darwin10-gcc-4.2.1 (GCC) 4.2.1 (Apple Inc. build 5666) (dot 3) Copyright (C) 2007 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. $ python Python 2.6.6 (r266:84292, Feb 15 2011, 01:35:25) [GCC 4.2.1 (Apple Inc. build 5664)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>>

Installing developer tools on Mac OS X

The developer tools (such as GCC) are an optional installation on Mac OS X. There are two ways to get those tools, both of which are free. On the OS X installation DVD is a directory labeled Optional Installs, in which there is a package installer for—among other things—the developer tools, including Xcode.

The other method is to download the latest copy of Xcode (for free) from

Most other POSIX-like systems, such as Linux, include a C compiler with the base system.

Installing from source for all POSIX-like systems

First, download the source from One way to do this is with your browser, and another way is as follows:

$ mkdir src $ cd src $ wget $ tar xvfz node-v0.10.7.tar.gz $ cd node-v0.10.7

The next step is to configure the source so that it can be built. It is done with the typical sort of configure script and you can see its long list of options by running the following:

$ ./configure –help.

To cause the installation to land in your home directory, run it this way:

$ ./configure –prefix=$HOME/node/0.10.7 ..output from configure

If you want to install Node in a system-wide directory simply leave off the -prefixoption, and it will default to installing in /usr/local.

After a moment it'll stop and more likely configure the source tree for installation in your chosen directory. If this doesn't succeed it will print a message about something that needs to be fixed. Once the configure script is satisfied, you can go on to the next step.

With the configure script satisfied, compile the software:

$ make .. a long log of compiler output is printed $ make install

If you are installing into a system-wide directory do the last step this way instead:

$ make $ sudo make install

Once installed you should make sure to add the installation directory to your PATHvariable as follows:

$ echo 'export PATH=$HOME/node/0.10.7/bin:${PATH}' >>~/.bashrc $ . ~/.bashrc

For cshusers, use this syntax to make an exported environment variable:

$ echo 'setenv PATH $HOME/node/0.10.7/bin:${PATH}' >>~/.cshrc $ source ~/.cshrc

This should result in some directories like this:

$ ls ~/node/0.10.7/ bin include lib share $ ls ~/node/0.10.7/bin node node-waf npm

Maintaining multiple Node installs simultaneously

Normally you won't have multiple versions of Node installed, and doing so adds complexity to your system. But if you are hacking on Node itself, or are testing against different Node releases, or any of several similar situations, you may want to have multiple Node installations. The method to do so is a simple variation on what we've already discussed.

If you noticed during the instructions discussed earlier, the –prefixoption was used in a way that directly supports installing several Node versions side-by-side in the same directory:

$ ./configure –prefix=$HOME/node/0.10.7


$ ./configure –prefix=/usr/local/node/0.10.7

This initial step determines the install directory. Clearly when Version 0.10.7, Version 0.12.15, or whichever version is released, you can change the install prefix to have the new version installed side-by-side with the previous versions.

To switch between Node versions is simply a matter of changing the PATHvariable (on POSIX systems), as follows:

$ export PATH=/usr/local/node/0.10.7/bin:${PATH}

It starts to be a little tedious to maintain this after a while. For each release, you have to set up Node, npm, and any third-party modules you desire in your Node install; also the command shown to change your PATHis not quite optimal. Inventive programmers have created several version managers to make this easier by automatically setting up not only Node, but npmalso, and providing commands to change your PATHthe smart way:

Run a few commands; testing the commands

Now that you've installed Node, we want to do two things; verify that the installation was successful, and familiarize you with the command-line tools.

Node's command-line tools

The basic install of Node includes two commands, node and node-waf. We've already seen nodein action. It's used either for running command-line scripts or server processes. The other, node-waf, is a build tool for Node native extensions. Since it's for building native extensions, we will not cover it in this book and you should consult the online documentation at

The easiest way to verify whether your Node installation works is also the best way to get help with Node. Type the following:

$ node –-help Usage: node [options] [ -e script | script.js ] [arguments] node debug script.js [arguments] Options: -v, --version print node's version -e, --eval script evaluate script -p, --print print result of --eval -i, --interactive always enter the REPL even if stdin does not appear to be a terminal --no-deprecation silence deprecation warnings --trace-deprecation show stack traces on deprecations --v8-options print v8 command line options --max-stack-size=val set max v8 stack size (bytes) Environment variables: NODE_PATH ':'-separated list of directories prefixed to the module search path. NODE_MODULE_CONTEXTS Set to 1 to load modules in their own global contexts. NODE_DISABLE_COLORS Set to 1 to disable colors in the REPL

Documentation can be found at

It prints the USAGEmessage, giving you the command-line options.

Notice that there are options for both Node and V8 (not shown in the previous command line). Remember that Node is built on top of V8; it has its own universe of options that largely focus on details of bytecode compilation or the garbage collection and heap algorithms. Enter node --v8-optionsto see the full list of them.

On the command line you can specify options, a single script file, and a list of arguments to that script. We'll discuss script arguments further in the next section, Running a simple script with Node .

Running Node with no arguments plops you in an interactive JavaScript shell:

$ node > console.log('Hello, world!'); Hello, world!

Any code you can write in a Node script can be written here. The command interpreter gives a good terminal-orientated user experience and is useful for interactively playing with your code. You do play with your code, don't you? Good!

Running a simple script with Node

Now let's see how to run scripts with Node. It's quite simple. Let's start by referring back to the helpmessage:

$ node –-help Usage: node [options] script.js [arguments]

It's just a script filename and some script arguments, which should be familiar for anyone who has written scripts in other languages.

Creating and editing Node scripts can be done with any text editor that deals with plain text files, such as vi/Vim, Emacs, Notepad++, jEdit, BBEdit, TextMate, or Komodo. It's helpful if it's a programmer-oriented editor, if only for the syntax coloring.

For this and other examples in the book, it doesn't really matter where you put the files. However, for neatness' sake, you could start by making a directory named node-web-devin the home directory of your computer, then inside that create one directory per chapter (for example, chap02and chap03).

First create a text file named ls.jswith the following content:

var fs = require('fs'); var files = fs.readdirSync('.'); for (fn in files) { console.log(files[fn]); }

Next, run it by typing the following command:

$ node ls.js app.js ls.js

This is a pale, cheap imitation of the Unix lscommand (as if you couldn't figure that out from the name). The readdirSyncfunction is a close analog to the Unix readdirsystem call (type man 3 readdirin a terminal window to learn more) and is used to list the files in a directory.

The script arguments land in a global array named process.argvand you can modify ls.jsas follows to see how this array works:

var fs = require('fs'); var dir = '.'; if (process.argv[2]) dir = process.argv[2]; var files = fs.readdirSync(dir); for (fn in files) { console.log(files[fn]); }

And you can run it as follows:

$ node ls2.js ~/node/0.10.7/bin node node-waf npm

Launching a server with Node

Many scripts that you'll run are server processes. We'll be running lots of these scripts later on. Since we're still in the dual mode of verifying the installation and familiarizing you with using Node, we want to run a simple HTTP server. Let's borrow the simple server script on the Node home page (

Create a file named app.jscontaining the following:

var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello, World!\n'); }).listen(8124, ''); console.log('Server running at');

And run it this way:

$ node app.js Server running at

This is the simplest of web servers you can build with Node. just visit your browser to see the Hello, World! message.

A question to ponder is why this script did not exit, when ls.jsexited. In both cases, execution of the script reaches the end of the script; in app.js, the Node process does not exit, while in ls.jsit does. The reason is the presence of active event listeners. Node always starts up an event loop, and in app.jsthe listenfunction creates an event listenerwhich implements the HTTP protocol. This event listener keeps app.jsrunning until you do something such as press Ctrl + C in the terminal window. In ls.jsthere is nothing that creates a long-running event listener, so when ls.jsreaches the end of its script, Node will exit.

npm – the Node package manager

Node by itself is a pretty basic system, being a JavaScript interpreter with a few interesting asynchronous I/O libraries. One of the things which makes Node interesting is the rapidly growing ecosystem of third party modules for Node. At the center of that ecosystem is npm. The modules can be downloaded at source and assembled manually for use with Node programs. The npmcommand gives us a simpler way; npmis the de-facto standard package manager for Node and it greatly simplifies downloading and using these modules. We will talk about npmat length in the next chapter.

The sharp-eyed will have noticed that npmis already installed via all the installation methods already discussed. In the past, npmwas installed separately, but today it is bundled with Node.

Now that we have npminstalled, let's take it for a quick spin. Hexy is a utility program for printing hex dumps of files. It serves our purpose right now in giving us something to quickly install and try out.

$ npm install -g hexy npm http GET npm http 200 npm http GET npm http 200 /opt/local/bin/hexy -> /opt/local/lib/node_modules/hexy/bin/hexy_cmd.js hexy@0.2.5 /opt/local/lib/node_modules/hexy

Adding the -gflag makes the module available globally, irrespective of which directory it is installed in. It is most useful when the module provides a command-line interface, because npmensures the command is installed correctly for use by all users of the computer.

Depending on how Node is installed for you, that may need to be run with sudo.

$ sudo npm install -g hexy

Once it is installed, you'll be able to run the newly installed program this way:

$ hexy --width 12 ls.js 00000000: 7661 7220 6673 203d 2072 6571 var.fs.=.req 0000000c: 7569 7265 2827 6673 2729 3b0a uire('fs');. 00000018: 7661 7220 6669 6c65 7320 3d20 var.files.=. 00000024: 6673 2e72 6561 6464 6972 5379 fs.readdirSy 00000030: 6e63 2827 2e27 293b 0a66 6f72 nc('.');.for 0000003c: 2028 666e 2069 6e20 6669 6c65 .( 00000048: 7329 207b 0a20 2063 6f6e 736f s).{...conso 00000054: 6c65 2e6c 6f67 2866 696c 6573 le.log(files 00000060: 5b66 6e5d 293b 0a7d 0a [fn]);.}.

Again, we'll be doing a deep dive into npmin the next chapter. The hexyutility is both a Node library and a script for printing out these old style hex dumps.

Starting Node servers at system startup

Earlier we started a Node server from the command line. While this is useful for testing and development, it's not useful for deploying an application in any normal sense. There are normal practices for starting server processes, which differ for each operating system. Implementing a Node server means starting it similarly to the other background processes (sshd, Apache, MySQL, and so on) using, for example, start/stop scripts.

The Node project does not include start/stop scripts for any operating system. It can be argued that it would be out of place for Node to include such scripts. Instead, Node server applications should include such scripts. The traditional way is that the initdaemon manages background processes using scripts in the /etc/init.ddirectory. On Fedora and Red Hat, that's still the process, but other operating systems use other daemon managers such as Upstart or launchd.

Writing these start/stop scripts is only a part of what's required. Web servers have to be reliable (for example auto-restarting on crashes), manageable (integrate well with system management practices), observable (saving STDOUTto logfiles), and so on. Node is more like a construction kit with the pieces and parts for building servers, and is not a complete polished server itself. Implementing a complete web server based on Node means scripting to integrate with the background process management on your OS, implementing the logging features you need, the security practices or defenses against bad behavior, such as denial of service attacks, and much more.

Here are several tools or methods for integrating Node servers with background process management on several operating systems, to implement continuous server presence beginning at system startup. In a moment we'll also do a brief walkthrough of using forever on a Debian server. You can run Node as a background daemon on different platforms using the following ways:

To demonstrate a little bit of what's involved, let's use the forevertool, along with an LSB-style init script, to implement a little Node server process. The server used to demonstrate this is a Debian-based VPS with Node and npminstalled in /usr/local/node/0.10.7. The following server script is in /usr/local/app.js(not the most correct place to install the app, because it's not quite compatible with the LSB-preferred locations for files, but useful for this demo).

#!/usr/bin/env node var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'); }).listen(1337);

Note the first line of the script carefully. It is a little bit of Unix/POSIX magic, which many readers will recognize, that helps to make the script executable. This executes the script, after first looking up the location of the "node" executable using the PATHenvironment variable. Any script you plan to execute directly should have this first line, plus have the execute permission set.

The forevertool is installed as follows:

$ sudo npm install -g forever

The forever script manages background processes. It can restart any processes that crash, send the standard output and error streams to log files, and has several other useful features. It's worth exploring.

The final bit in getting this to work is a shell script, /etc/init.d/node, that acts as an initscript to manage this server:

#! /bin/sh -e set -e PATH=/usr/local/node/0.10.7/bin:/bin:/usr/bin:/sbin:/usr/sbin DAEMON=/usr/local/app.js case "$1" in start) forever start $DAEMON ;; stop) forever stop $DAEMON ;; force-reload|restart) forever restart $DAEMON ;; *) echo "Usage: /etc/init.d/node {start|stop|restart|force-reload}" exit 1 ;; esac exit 0

On Debian you set up an initscript with this command:

$ sudo /usr/sbin/update-rc.d node defaults

This configures your system so that /etc/init.d/nodeis invoked on reboot and shutdown, to start or stop the background process. During boot-up or shutdown. Each initscript is executed, and its first argument is either startor stop. Therefore, when our initscript is executed during boot-up or shutdown one of these two lines will be executed:

start) forever start $DAEMON ;; stop) forever stop $DAEMON ;;

We can run the initscript manually:

$ sudo /etc/init.d/node start info: Running action: start info: Forever processing file: /usr/local/app.js

Because our initscript uses the forevertool, we can ask foreverthe status of all processes it has started:

$ sudo forever list info: Running action: list info: Forever processes running [0] node
/usr/local/app.js [16666, 16664] /home/me/.forever/7rd6.log 0:0:1:24.817

With the server process running on your server, you can open it in a browser window to see the Hello World message. With it still running and managed by foreverwe have these processes:

$ ps ax | grep node 16664 ? Ssl 0:00 node
/usr/local/node/0.8.16/bin/forever start /usr/local/app.js
16666 ? S 0:00 node /usr/local/app.js

When you're done playing with this you can shut it down this way:

$ sudo /etc/init.d/node stop info: Running action: stop info: Forever processing file: /usr/local/app.js info: Forever stopped process: [0] node /usr/local/app.js [5712, 5711]
/home/me/.forever/Gtex.log 0:0:0:28.777
$ sudo forever list info: Running action: list info: No forever processes running


We learned a lot in this chapter, about installing Node, using its command-line tools, and how to run a Node server. We also breezed past a lot of details that will be covered later in the book, so be patient.

Specifically, we covered:

  • Downloading and compiling the Node source code
  • Installing Node either for development use in your home directory, or for deployment in system directories
  • Installing Node Package Manager (npm), the de-facto standard package manager used with Node
  • Running Node scripts or Node servers
  • What's required to use Node for a reliable background process

Now that we've seen how to set up the basic system, we're ready to start working on implementing applications with Node.

Resources for Article :

Further resources on this subject:

You've been reading an excerpt of:

Node Web Development

Explore Title