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.

5 comments:

  1. nicee... :)
    would be great if you can also list down on ways of using the technology . apart from Hosting Simple Javascript WebServer, I believe you can also use Node Js for its Async behavior with its powerful JS API.. your thoughts ??

    ReplyDelete
    Replies
    1. Thanks Jilesh. Appreciate your feedback. I will cover some of the key strengths is the next post.

      Delete
  2. This comment has been removed by the author.

    ReplyDelete
  3. Would love to see you highlight on its one of core strength i.e. event driven approach and being dynamic lang...

    Do you think this approach challenges traditional web containers such as tomcat and can be 100% answer to it?

    ReplyDelete
    Replies
    1. Scripting languages have been a natural choice for heavy duty web sites for a long time. But they may not replace Java containers, at least in near future, IMO.

      Delete