Update: The node.js api is in constant flux until it reaches a 1.0 release. The code in this post doesn’t work with the latest releases of node (it was written for the 0.1.3x series), however the concept is still the same. The best place to start is the node.js api docs.
I’ve only just got round to doing some coding with Ryan Dahl’s great node.js project, although the project has been around for about a year now, so I’ve put together this short introduction to give you a taste of what node is about.
The project is under heavy development, and the api is still changing quite regularly, but don’t let that scare you off, node is stable and usable now.
Node uses this to it’s full advantage, most operations that you perform in node will have a callback associated with it, this means that node doesn’t have to wait while it’s completing some time-consuming task, it can go about serving other requests, then when the event is fired it can go back and execute the function attached to the event. This leads to very fast response times when using node as a web server, as it can handle thousands of requests per second.
The program can be installed easily on OS X (using Homebrew or compile from source) and Linux (compile from
source), Windows support is planned in the future, but is currently non-existent. Once installed you have access to a
command line utility,
node, this runs .js files through the node interpreter.
A basic node hello world program could look like this:
save this into a file and then run it from the command line like so:
Each module is a self contained unit of code, it has its own private scope, so can define functions to use internally, then expose public functions to be used externally using the exports object. Here’s an example of a simple module:
The last line may seem a little strange, but all it does is extend the exports object with the properties defined in the calculator object, if that line wasn’t there then the module wouldn’t return anything as it wouldn’t export anything. To use our new (rather basic) module we’d do something like this:
This overview barely scratches the surface of what is possible with node.js, the api documentation contains all you need to know about node, and it is all on one (albeit rather long) page, so once you’ve read through it you should have a pretty good idea how you’d go about coding for it.
There are already some very interesting projects using node available to try. A quick glance at the node wiki will give you a glimpse of what is possible with this fantastic new technology, as well as some more background information on the project.