Monday 28 April 2014

Hello World with Node.js



First things first. Read the blog header :-).

If you have hammer as the only tool, you tend to look at every problem as a nail. Have you seen this happening in your work environment ?

This blog is meant to provide a very quick introduction to different emerging technologies and provide a "Hello World application" that gets you started.


Technology Type
Node.js is a server side scripting technology. It can be considered to be a main-stream server technology. It's even available on Amazon EC2 and Heroku. 
Base technology
Javascript
Why use this technology
You may want to check a good article on Node.js  http://www.toptal.com/nodejs/why-the-hell-would-i-use-node-js
Ideal for
Web applications serving high scale. If you want to use web sockets, Node.js is a great option.
Not ideal for
Compute intensive applications (e.g. complex algorithms)

To get started with Node.js, download the latest version of Node.js from http://nodejs.org Its a small installer (around 6 MB size).

Install Node.js.

We will create Hello World program as follows:

helloworld.js:

var http = require('http');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(1234, '127.0.0.1');

console.log('Server running at http://127.0.0.1:1234/');

This code creates a HTTP Server, binds it with port 1234 and returns "Hello World" for each HTTP request.

Now save this file as helloworld.js on your file system, open the command prompt, set the path of the Node.js binary in your environment, and run the program as 

node helloworld.js

Open your favourite browser and type http://127.0.0.1:1234/

Your Hello World program for Node.js is done.

Welcome to Node.js !

Isn't it cool ?  Do you want to write a HTTP server in the language / technology of your choice ? Is it easy / difficult compared to Node.js ? Try it out and find for yourself.  Happy coding.

If you are interested in this blog, subscribe to the blog to receive new posts. Comments are welcome.