Thursday, April 11, 2013

Getting started with Node.js

I've read and heard a lot of good things about Node.js over the last year or so. I first learned of it while I was doing a little research into Cloud Platforms such as Heroku and dotCloud back in 2011. At first I, as many others, was a little dubious about how well Javascript would perform as the basis of an entire web application. Nevertheless, after seeing a short presentation that a co-worker had prepared for the JavaScript Leeds User Group last year, I was certainly keen to see more.

A lot has happened to me since then and I've spent much of that time working with JSF but I finally got around to installing Node onto my dev box. To get started you can start from scratch with some plain old Javascript such as the example on the node site:
var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
This would be saved to a file such as server.js which can then be run with: 'node server.js'.

It's a little more productive to use one of the available frameworks to get going though. I did a little research and chose to use Express to get started.

Express can be downloaded via the Node Package Manager (npm). It's worth doing a global install, which can be done using the -g option:
sudo npm install -g express
Now that express is installed we can use it to generate the basic structure of our webapp (I use -c less here to enable support for LESS):
express -c less myapp
This creates a directory named 'myapp' that contains everything we need to get started. In that directory you'll see 'package.json' which should contain something similar to:
{
  "name": "application-name",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node app.js"
  },
  "dependencies": {
    "express": "3.4.0",
    "jade": "*",
    "less-middleware": "*"
  }
}
Running 'npm install' from within the directory will then cause the Node Package Manager to download the specified dependencies to a sub folder called 'node_modules'. You can view the downloaded packages by running 'npm ls'.

There is also a file called 'app.js' which is similar to the basic example taken from the node website shown earlier. Run 'node app.js' to start the server running, you'll then be able to see the default page in your browser by going to localhost on the specified port.