Thursday, July 15, 2010

Getting started with node.js and CoffeeScript

After a couple of month the voices saying Node.js is awesome getting louder and louder, I decided to give it a try.

There is something different I never played with but I absolutly need to: CoffeeScript. I was quite amazed to find out, that those two new shiny things fit and work perfectly with one another. If you like to get Node and CoffeeScript up and running just follow my little tutorial. Its written for Mac but it should work for Linux too.

To get started first install Node.js. So lets grep the latest version directly from github at http://github.com/ry/node or download the tar-archive from http://nodejs.org/#download. To build and install Node type:

./configure
make
sudo make 

To install CoffeeScript go and clone the Node Package Manager from http://github.com/isaacs/npm.

git clone http://github.com/isaacs/npm.git
switch to the nmp directory and type
sudo make

The latest stable CoffeeScript-version will be installed to you computer. Now you have binary called "coffee", which just starts your CoffeeScripts with Node.

If you're a TextMate fangirl or fanboy you may want to install the CoffeeScript TextMate bundle. It can be found at http://github.com/jashkenas/coffee-script-tmbundle.

Ok, now you ready to play. Here is a hello world server written in CoffeeScript:

server = require('http').createServer (request, response) ->
    response.writeHead 200, {'Content-Type': 'text/plain'}
    response.end 'Hello World'
server.listen 8124
console.log 'Server running at http://0.0.0.0:8124/'
Save it as hello_world.coffee and run it with:
coffee hello_world.coffee

Open http://0.0.0.0:8124/ to see "Hello World" in your Browser.

Just take a look to the JavaScript version:
var server = require('http').createServer(function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/plain'});
  response.end('Hello World');
})
server.listen(8124);
console.log('Server running at http://0.0.0.0:8124/');

Although it's a short and dead simple script, for me the Coffee version is much cleaner and readable.

Cheers!