FAQ: Node.js

Image

JavaScript on the server? Surely you can’t be serious…

I thought JavaScript was a piddly little toy language built into web browsers to add irritating animations and other useless fluff to web pages?

We still have nightmares about GeoCities too, and yes, JavaScript has historically been used for things like that. It originated at Netscape in the mid 90s as a lightweight scripting language to add interactive properties to web pages, but it has come a long way since then. Sure, many programmers look down on JavaScript, and it’s massively overused on some websites, but it also has plenty of fans.

After all, it’s easy to pick up: anyone with access to a web browser can start playing around with JavaScript code. You don’t need to install compilers, IDEs or other specialist tools. And its syntax isn’t a million miles away from C/Java/C# and similar languages, so it doesn’t look completely foreign at first glance for many coders.

So what’s Node.js, and why do I keep hearing about it?

Until recently, JavaScript was only used as a client-side language – that is, running inside web browsers on end-user machines.
Node.js changes all this and puts JavaScript on the server. It’s a platform and runtime environment for building internet applications, and has some features that make it especially attractive for web developers.

Oh right, so it’s yet another framework-du-jour written by some latte-supping hipsters who think they’re going to make £squillions, but the whole thing will be abandoned before version 0.01?

Whoa, slow down cowboy! Respect to your cynicism, because there are a million and one so-called “revolutionary” platforms and frameworks out there, but Node.js is different. For starters, it’s actually being used – and not just by a couple of startups trying to do things differently. Node.js is being used by giants like Yahoo, Microsoft, SAP, Walmart, Groupon (of Gnome trademark trolling fame) and PayPal.

These companies are big and conservative, and wouldn’t rely on Node.js if it were immature or incomplete. Sure, the version number doesn’t given the impression that it’s ready for widespread usage – the latest release at the time of writing being 0.12 – but it’s doing real-world jobs out there on the web.

Fair enough. So what makes it great?

Node.js is excellent for building real-time web apps which have many concurrent connections, like chat sites and games. It has an event-driven architecture and non-blocking I/O, which helps makes it responsive and scalable. Plus, it runs on Google’s V8 JavaScript engine, as used in Chrome; this compiles JavaScript to machine code before executing it, so it’s not sluggish like you might expect.

Node.js operates on a single thread, so when you have hundreds or thousands of concurrent connections, you don’t lose performance due to thread context switches. On the downside, this means that Node.js apps can’t run across multiple CPU cores, so that’s potentially limiting for some tasks. But for real-time apps, it’s very good indeed.

So what do Node.js programs look like?

A good way to demonstrate how Node.js works is with a simple web application. Look at the screenshot on the opposite page: this shows a short Node.js program (test.js) being edited in Vim. This program creates an HTTP server running on port 8000 which returns “Hello, world!” with any browser request. You don’t need Apache, Nginx or any other separate web server with Node.js – you can do it all with the supplied modules.

Let’s go through the code: in the first line we require the ‘http’ module that’s included with Node.js and make it accessible via a variable of the same name. We now use the createServer() function of this module to make a new web server, which returns an object that we call server. But something very unusual is happening here: the createServer function takes another function as its parameter.

You see, when this Node.js program is running, the function passed to createServer will be called whenever a HTTP request is made (in other words, whenever a browser accesses the site). In this code, we don’t provide the name of a function and then write the function elsewhere; we put the function right inside of createServer(). This is known as an anonymous function, as it has no identity and can’t be used anywhere else.

Next, this anonymous function takes two parameters, and then sends a 200 status code and “Hello, world” text back to the browser. In the final line of the code, the server is set to listen on port 8000. So when this program is run with node test.js, and the user accesses http://localhost:8000, they will see the “Hello, world” message.

Wow, that’s a bit brain-bending!

Yes – if you’ve never done this sort of coding before, it can take a while to get your head around. And we don’t want to turn this into a full-on programming tutorial, so if you’d like us to cover Node.js application development in more detail, drop us a line. But still, this simple program demonstrates how JavaScript, Node.js and event-driven asynchronous callbacks work together to make useful software without reams of code.

Image

A simple Node.js application – note how an anonymous function is placed in the call to http.createServer().

This all sounds rather low-level. Are web application developers supposed to do a lot of grunt work by hand?

No, because there’s a growing range of web application frameworks built on top of Node.js, such as Express (www.expressjs.com) and SailsJS (www.sailsjs.org). These provide higher-level APIs and additional modules to speed up development of Node.js apps. Many of these are in the early stages of development, however, and it’ll take a while before the dust settles and we see who’s really in it for the long run.

Another ace Node.js has up its sleeve is its package manager, npm. This is a command-line tool that lets you install modules and manage dependencies, much like you would with a regular Linux package manager. At the time of writing, over 137,000 packages were available on www.npmjs.com – including database drivers, image file generators and monitoring tools. So whatever you need to do in your
Node.js app, chances are that someone has already written a module for it. But again, the vast majority of these are in the very early stages of development, so expect bugs and limitations.

Is the Node.js community one big, happy family, or has someone forked it yet?

Yes, there is a fork called io.js (https://iojs.org) which came about for various reasons. One major concern was that Node.js, under the corporate governance of San Francisco-based company Joyent, was taking much too long to reach version 1.0. The io.js project is already at version 1.6.3, suggesting that it’s mature and won’t drastically change under developers’ feet, and the development team has opted for a more open system of management, with a technical committee comprised of the software authors.

Still, Node.js isn’t going anywhere, and despite the low version number its usage is increasing rapidly. As well as running on Linux and the BSDs, Node.js also works on Mac OS X, Windows, Solaris and other platforms. It’s released under the MIT licence, a permissive licence which makes the source code available but also allows for reuse within proprietary software.

OK, you’ve piqued my interest. Where do I go to find out more, and begin a new lucrative career as a Node.js application developer?

Your first port of call should be https://nodejs.org, which has a detailed list of all the APIs (see the Docs tab). If you already know a bit of JavaScript, you can install Node.js and then enter sudo npm install learnyounode -g to install a menu-driven tutorial explaining the basics (enter learnyounode to start it). You can find another good beginner’s guide at http://nodeguide.com/beginner.html, and if you’ve never written a single line of JavaScript in your life, try Mozilla’s great entry-level tutorial at http://tinyurl.com/mozjstut.