Thursday 1 August 2013

node.js + coffeescript in a nutshell

Here's is a quick 101 on getting Node.js/CoffeeScript up on Ubuntu Server I'm using Ubuntu 13.10 that contains Node.js in its default repositories. *Note that this will not be the newest one. However it's the simplest way of getting started.

We just have to use the apt package manager. We should refresh our local list packages before installing:

sudo apt-get update

sudo apt-get install nodejs

This is all that you need to do to get set up with Node.js. You will also need to install npm(Node.js Package Manager).

sudo apt-get install npm

This will allow you to easily install modules and packages to use with Node.js.

Because of a conflict with another package, the executable from the Ubuntu repositories is called nodejs instead of node. It's just good to keep this in mind.

The last step is to install the CoffeeScript interpreter

npm install coffee-script

Now that we are setup. Here is a basic node HelloWorld server written in coffee. File: index.coffee
http = require "http"
url = require "url"

start = () ->
 onRequest = (request, response) ->
  pathname = url.parse(request.url).pathname
  console.log ("Request for #{pathname}")
  
  response.writeHead (200),
  "Content-Type": "text/plain"

  response.write "Code Sandwich"
  response.end()
 
 http.createServer(onRequest).listen (8888)

 console.log ("Server has started.")
 
start()

Ladies start your servers.

coffee index.coffee

now check that this is all ok

localhost:8888