A Not Very Short Introduction To Node.js

Node.js is a set of asynchronous libraries, built on top of the Google V8 Javascript engine. Node is used for server side development in Javascript. Do you feel the rush of the 90′s coming through your head. It is not the revival of LiveWire, Node is a different beast. Node is a single threaded process, focused on doing networking right. Right, in this case, means without blocking I/O.

All the libraries built for Node use non-blocking I/O. This is a really cool feature, which allows the single thread in Node to serve thousands of request per second. It even lets you run multiple servers in the same thread. Check out the performance characteristics of Nginx and Apache that utilize the same technique.

Concurrency x Requests

The graph for memory usage is even better.

Concurrency x Memory

Read more about it at the Web Faction Blog

OK, so what’s the catch? The catch is that all code that does I/O, or
anything slow at all, has to be called in an asynchronous style.

So, all libraries that deal with IO has to be re-implemented with this
style of programming. The good news is that even though Node has only
been around for a couple of years, there are more than 1800 libraries
available. The libraries are of varying quality but the popularity of
Node shows good promise to deliver high-quality libraries for anything
that you can imagine.

History

Node is definitely not the first of its kind. The non-blocking
select() loop, that is at the heart of Node, dates back to 1983.

Twisted appeared in Python (2002) and EventMachine in Ruby (2003).

This year a couple of newcomers appeared.

Goliath, which builds on EventMachine, and uses fibers to allow us to program in an synchronous style even though it is asynchronous under the hood.

And, the Async Framework in
.Net
, which enhances the compiler with the keywords async and await to allow for very elegant asynchronous programming.

Get Started

This example uses OSX as an example platform, if you use something else
you will have to google for instructions.

When installed you have access to the node command-line command. When
invoked without arguments, it start a REPL.

When invoked with a script it runs the script.

Networking

As I mentioned above, Node is focused on networking. That means it
should be easy to write networking code. Here is a simple echo server.

And here is a simple HTTP server.

Quite similar. A cool thing is that the servers can be started from the
same file and node will, happily, serve both HTTP and echo requests from
the same thread without any problems. Let’s try them out!

Modules

Node comes with a selection of built in modules. Ryan Dahl says that
they try to keep the core small, but even so the built-in modules cover
a lot of useful functionality.

  • net – contains tcp/ip related networking functionality.
  • http – contains functionality for dealing with the HTTP protocol.
  • util – holds common utility functions, such as log, inherits, pump,
  • fs – contains filesystem related functionality, remember that
    everything should be asynchronous.
  • events – contains the EventEmitter that is used for dealing with
    events in a consistent way. It is used internally but it can be used
    externally too.

An example

Here is an example of a simple module.

As you can see it looks like a normal Javascript file and it even looks
like it has global variables. It doesn’t. When a module is loaded it is
wrapped in code, similar to this.

As you can see the code is wrapped in a function and an empty object
with an export property is sent into it. This is used by the file to
export only the functions that it want to publish.

The require function works in symphony with the module and it returns
the exported functions to the caller.

Node Package Manager, npm

To allow simple handling of third-party packages, Node uses npm. It
can be installed like this:

And used like this:

As you can see, installing a module also installs its dependencies. This
works because a module can be package with meta-data, like so:

The package.json contains information about who made the module, its
dependencies, along with some additional information to enable better
searching facilities.

Npm installs the modules from a common
respository
, which contains more than 1800
modules.

Noteworthy Modules

Express is probably the most used of all third-party modules. It is
a Sinatra clone and it is very good, just like Sinatra.

Express uses Connect to handle middleware. Middleware is like Rack
but for Node (No wonder that Node is nice to work with when it borrows
its ideas from Ruby :)

Another popular library is Socket.IO. It handles the usual socket
variants, such as WebSocket, Comet, Flash Sockets, etc…

MySql has a library for Node.

And Mongoose can be used for accessing MongoDB.

Templating Engines

Everytime a new platform makes its presence, it brings along a couple of
new templating languages and Node is no different. Along with the
popular ones from the Ruby world, like Haml and Erb (EJS in Node),
comes some new ones like Jade and some browser templating languages like
Mustache and jQuery templates. I’ll show examples of Jade and Mu
(Mustache for Node).

I like Jade, because it is a Javascript dialect of Haml and it seems
appropriate to use if I’m using Javascript on the server side.

I’m not really sure if I like Mustache or not, but I can surely see the
value of having a templating language which works both on the server side
and in the browser.

Testing

Node comes with assertions built in, and all testing frameworks build on
the Assert module, so it is good to know.

Apart from that there are at least 30 different testing frameworks to
use. I have chosen to use NodeUnit since I find that it handles
asynchronous testing well, and it has a nice UTF-8 output that looks
good in the terminal,

Deployment

There are already a lot of platforms providing Node as a service (PaaS
, Platform as a Service). Most of them are using
Heroku style deployment by pushing to a Git remote.
I’ll show three alternatives that all provide free Node hosting.

Joyent (no.de)

Joyent, the employers of Ryan Dahl, give you ssh access so that you
can install the modules you need. Deployment is done by pushing to
a Git remote.

Nodester

Nodester, gives you a command line tool, nodester, that you use to
install modules. Deployment by pushing to a Git remote.

Cloud Foundry

Cloud Foundry is one of the most interesting platforms in the cloud. It
was genius by VM Ware to open source the platform, allowing anyone to
set up their own cloud if they wish. If you don’t want to setup your own
Cloud Foundry Cloud, you can use the service hosted at
cloundfoundry.com.

With Cloud Foundry, you install the modules locally and then they are
automatically deployed as part of the vmc push. Push in this case does
not mean git push, but instead, copy all the files from my local machine
to the server.

Tools

There are of course a bunch of tools that come with a new platform,
Jake, is a Javascript version of Rake, but I am happy with Rake and
I don’t see the need to switch. But, there are some tools that I cannot
live without when using Node.

Reloaders

If you use the vanilla node command then you have to restart it
every time you make a change to a file. That is awfully annoying and
there are already a number of solutions to the problem.

Debuggers

Another tool that it is hard to live without is a debugger. Node comes
with one built in. It has a gdb flavor to it and it is kind of rough.

If you want a GUI debugger, it is possible to use the one that comes with
Chrome by installing the node-inspector. It is started similarly to
the built in debugger, but the --debug is an option instead of
a subcommand.

After that you can just fire up Chrome on the URL,
http://0.0.0.0:8080/debug?port=5858 and you can debug the node process
just as if it was running in the browser.

Idioms

Idioms, patterns, techniques, call it what you like. Javascript code is
littered with callbacks, and event more so with Node. Here are some tips
on how to write good asynchronous code with Node.

Return on Callbacks

It is easy to forget to escape from the function after a callback has
been called. An easy way to remedy this problem is to call return before
every call to a callback. Even though the value is never used by the
caller, it is an easy pattern to recognize and it prevents bugs.

Exceptions in Callbacks

Exceptions that occur in callbacks cannot be handled the way we are used
to, since the context is different. The solution to this is to pass
along the exception as a parameter to the callback. In Node the
convetion is to pass the error as the first parameter into the callback.

Parallel Execution

If you have multiple tasks that need to be finished before you take some
new action, this can be handled with a simple counter. Here is an
example of a simple function that starts up a bunch of functions in
parallel and waits for all of them to finish before calling the
callback.

Sequential Execution

Sometimes the ordering is important. Here is a simple function that
makes sure that the calls are executed in sequence. It uses recursion to
to make sure that the calls are handled in the correct order. It also
uses the Node function process.nextTick() to prevent the stack from
getting to large for large collections. Similar results can be obtained
with setTimeout() in browser Javascript. It can be seen as a simple
trick to achieve tail recursion.

Library Support for Asynchronous Programming

If you don’t want to write these functions yourself, there are a few
libraries that can help you out. I’ll show two version that I like.

Fibers

Fibers are also called co-routines. Fibers provide two functions,
suspend and resume, which allows us to write code in a synchronous
looking style. In the Node version of fibers,
node-fibers, suspend and
resume are called yield() and run() instead.

Fibers are a very nice way of writing asynchronous code but, in Node,
they have one drawback. They are not supported without patching the V8
virtual machine. The patching is done when you install node-fibers and
you have to run the command node-fibers instead of node to use it.

The async Library

If you don’t want to use the patched version of V8, I can recommend the
async library. Async provides
around 20 functions that include the usual ‘functional’ suspects (map,
reduce, filter, forEach…) as well as some common patterns for
asynchronous flow control (parallel, series, waterfall…). All these
functions assume you follow the Node convention of providing a single
callback as the last argument of your async function.

Conclusion

Node is definitely an interesting platform. The possibility to have
Javascript running through the whole stack, from the browser all the way
down into the database (if you use something like CouchDB or MongoDB)
really appeals to me. The easy way to deploy code to multiple, different
cloud providers is also a good argument for Node.

5 Comments

  1. Roger Schildmeijer

    Interesting article about node.js. (You might want to add Deft to the History section, in conjunction with Goliath e.g. Deft: https://github.com/rschildmeijer/deft) disclaimer: Im a Deft committer

  2. As already mentioned, nice article! Wanted to add that while developing my experimental ‘template’ like system WebGenJS (yes, another shameless plug; https://github.com/ernstsson/WebGenJS) I’ve been using whiskey (https://github.com/cloudkick/whiskey) for unit testing. It has a very nice node-jscoverage integration for code coverage reports. Very useful!

  3. @Roger, Deft looks interesting, especially the performance graphs!
    @Magnus, I agree, whiskey looks good. Thanks for the tip.

  4. Gunnar Liljas

    Nice article, and anything that mentions tapirs is a win in my book.

  5. @Gunnar, I hear you :)

Leave a Reply