Introduction
nodejs is here, it’s going to save the world, long live Javascript!
Oh really?
As Chuck D says “Don’t believe the Hype”, however I’ve been using nodejs for a year or so and I quite like it.
Server side Javascript?
Well it is the simplest definition, but not 100% accurate. Yes, nodejs code is written in Javascript (the clue is in the js part of the name), but it’s actually defined as Event Driven, Asynchronous IO.
- Event Driven – eventing is built into the framework, which allows us to pass messages/commands in a nice OO friendly manor (tell don’t ask)
- Asynchronous IO – input and output does not block, which means no need for complex thread management
What do I need?
nodejs runs on Windows and Linux (I’d recommend the latter), it can be downloaded from here or directly from the git repository.
Fisherprice, my first node app
require('http')
.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello World');
})
.listen(1337);
console.log('Server running');
To execute the code we execute node from the command line, using the file name as an argument, e.g.
node helloWorld.js.
This code creates an app that is hosted at http://localhost:1337, when this address is hit the response will be a HTTP 200 (success) with the text ‘Hello World’. Pretty simple and no need for hosting in a separate web server*.
We can also rewrite this example to work with net.tcp:
require('net')
.createServer(function (socket) {
socket.write('helloWorld')
})
.listen(1330);
It’s all about the modules
You probably noticed the require keyword in the above examples, which is a request to load up a named module. This is possible because nodejs implements the CommonJS standard of defining and loading modules.
This allows us to define our own modules, like so:
var helloWorlder = function(){
return 'hello world';
};
exports.helloWorlder = helloWorlder;
The exports object allows us to define the API of our module, in this case this is just a simple ‘hello World’ function. If this is saved in a file named aModule.js, then we can utilise this in another node application like so:
var module = require('./aModule.js');
console.log(module.helloWorlder());
Open source == Communism?
Of course, it would be dull world if we kept our node modules to ourselves. nodejs is all about open source and sharing our code, and this is where Node Package Manager (NPM) comes in.
NPM allows you to consume open source node modules and also submit your own. After installation NPM allows you to install modules at the command line, such as the following example for underscore:
NPM install underscore
After successfully running this command, you can then use underscore in your node app:
_ = require('underscore');
var collection = [1,2];
console.log(_.first(collection));
Good practice -> node modules differ from the large client side libraries (e.g. jQuery, Mootools etc), they tend to be smaller and focussed on one particular task.
Eventing
This often overlooked feature of node is implemented through the EventEmitter class, which allows code to publish messages/commands to other subscribing sections of code. Here is an example of a direct use of the event emitter:
var EventEmitter = require('events').EventEmitter;
var publisher = new EventEmitter();
publisher.on('stuff', function(){
console.log('stuff event fired');
});
publisher.on('stuff', function(){
console.log('other stuff event fired');
});
publisher.emit('stuff');
When this code is executed the emit call will output the following to the console:
stuff event fired
other stuff event fired
Classes can also inherit from the EventEmitter, allowing them to have their own dedicated subscribers that they can emit to (see my node shopping cart kata for an event driven node solution).
Lessons Learnt
- Unit Testing – There is a node port of Jasmine, but I’d recommend Vows, which is an asynchronous unit testing framework designed for use with node
- Coffeescript – This is a language that compiles down into Javascript, it gives you a more ruby like syntax and much easier construction of classes and inheritance. Although the outputted Javascript is a bit too verbose for client side code, it is great for node. More details here.
- MVC – Express is a lightweight MVC framework for node (think more Sinatra/Nancy rather than ASP.NET MVC).
- Development – NodeMon can be used to watch files in a directory and restart your node application if they change.
Other useful links
Github repository containing the examples from this post.
Github repository of the shopping kata in nodejs.
Introduction to nodeJs by the creator Ryan Dahl.
@nodejs
@ryah
* Okay, it probably is a good idea to host behind a web server for web facing services, many leading web servers now have support for nodejs processes.





