Getting started with NodeJs Part-2 : Write simple web server in NodeJs

we have seen the setup of Nodejs on windows box in  last post.

Today we will have a look how we can write a simple web server which respond “Hello World” to our request


1. Open your favorite editor (i.e Notepad)  I personally like “Sublime Text 2”

2. copy the code below and save your file with “HelloWorld_Server.js”


Author : Dilip Singh

HomePage :

Sample : Hello world sample in NodeJs

Description : Simple hello world example

To test the sample , type into browser address bar ‘http://localhost:8080’

You should see the response ‘Hello World’



// htp module required to create http server

var http = require(‘http’);

var server = http.createServer();


//this function will handle all the requests to this server

function handleMyAllRequests(req,resp)


// create here message

resp.writeHead(200, {“content-type”:”text/plain”});

resp.write(“Hello World”);

resp.end();// you can also write more string in the construct of end() function.



// on every request event handleMyAllRequests function will be callled

server.on(‘request’, handleMyAllRequests);


// assign a port to the server


console.log(‘server is listening at’);

3. Now go to command prompt and type :

c:\><directory of your file> > Node HelloWorld_Server.js

4. Press Enter .You should see the server log that its started.

5.  Go to web browser and type address “http://localhost:8080&#8221;

you will see the response from your first nodejs server

Code Explanation

In NodeJs, we need to import the ‘module’ for type of work we want to perform . In the example above we have imported module ‘http’. A module in

imported using require() function.

You can also optimise your code above 

// http module required to create http server

require(‘http’).createServer().on(‘request’, function handleMyAllRequests(req,resp){

// create here message

resp.writeHead(200, {“content-type”:”text/plain”});

resp.end(“Hello World with optimised code “);

} ).listen(8080);



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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s