Friday, October 26, 2012

Getting Started with node.js on Ubuntu

This is a small getting started guide for getting up and running with node.js on Ubunutu.

Step 0: DON'T install node.js from Ubuntu Software Center.
When I started messing about with node.js the first thing I did was to install node.js from Ubuntu Software Center. But soon I started using it I realised that some of the stuff that my friends where using, like npm ( more on that later ) was missing. I check the version and realised that the version I got from UBC was 0.2.6 while the latest verision was 0.8.12. So i quickly removed it from UBC and headed online.

Step 1: Install from nodejs.org  
Head to http://nodejs.org
Clicking the "Install" link will give you the latest version tar.gz
Extract the content to somewhere good, this example i will use ~/code/
Enter your terminal and go to the folder, cd ~/code/node-v0.8.12
Read through README.md carefully ( lol! )
>./configure
stuff happen
>make
more stuff happen
>sudo make install

Restart your terminal


Step 2: Start Server
Copy the following code to a file called node_js_getting_started.js
var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Running node.js\n');
}).listen(1234, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1234/');
Or download the file here node_js_getting_started.js

Now run the command >node node_js_getting_started.js
And you should see
Server running at http://127.0.0.1:1234/

Step 3: Test it
Open a browser and go to http://127.0.0.1:1234/
and now you should see "Running node.js" in your browser.
We got a webserver with node.js up and running! Yay!