Node.js Hello world code

Let me write the program and will explain line by line.

http = require(‘http’)
    res.writeHead(200, {‘content-Type’:’text/html’});
    res.write(“<h1>Hello Word!</h1>”)
    res.end(“<h2>This is the end!</h2>”);
}).listen(3000, “”);
console.log(“Server running at;)

Let’s create a new file called hello_world.js.

Now Node comes with a handfull of libraries to make the development of event-based servers easy.

To use one of the available libraries, We simply include its module using the require function.

http_object = require(‘http’)

The require function will return an object representing the module that you pass into it and you can capture that object in a variable.


For running app, we need to create HTTP server.  Node provides the http library. With reference to http_object create server.


The createServer that takes a callback function and returns a new server object.

The callback function is what Node calls a listener function and it is called by the server whenever a new request comes in.

Whenever an HTTP request is made, the listener function will be called and objects representing the HTTP request and response will be passed into the function.


Then first need to write the appropriate HTTP headers.

res.writeHead(200, {‘content-Type’:’text/html’});

The writeHead function takes a couple of arguments. The first is an integer value representing the status code of the request which for us will be 200, in other words,

Then we’ll call the write function and pass in the data that you wish to send.

 res.write(“<h1>Hello Word!</h1>”)

Now that we’ve created our server, we need to set it up to listen for new requests.

listen(3000, “”);

The listen function on our server object and pass in a port number for it to listen on(3000). The listen function also takes an optional second parameter which is the hostname URL(“”),

Finally, let’s print out a message to let us know that our server is running

console.log(“Listening on“).

There we go, now let’s run our app by calling node and passing to it the name of the file we want it to execute.

node hello_world.js and open browser “

That’s it. Enjoy………………..


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s