Create Basic HTTP Server with Node.js

10 / May / 2013 by Amit Kumar 0 comments

Like other languages(Java, php), we do not need to set up any Apache HTTP server. With Node, things are a bit different, with Node.js, we not only implement our application, we also implement the whole HTTP server. In fact, our web application and its web server are basically the same. Lets create a basic Node HTTP server. First let’s create a main file called server.js in the root directory which we use to start our application, and a module file where our HTTP server code lives, and fill it with the code given below:

var http = require("http");
var requestHandler = function(request, response) {
  console.log("Request received.");
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello World");
  response.end();
};
var server = http.createServer(requestHandler);
server.listen(9999);
console.log("Server has started.");

Now run the code. To run the server.js script with Node.js type below command:

node server.js

Now open your favorite browser and hit it at http://localhost:9999/. This should display a web page that says “Hello World!”. Well, now lets analyze what’s actually going on here.

1. The first line requires the http module that ships with Node.js and makes it accessible through the variable http.
2. We definded a requestHandler funciton to handle all the requests.
3. We called one of the functions that http module offers: createServer. This function returns an object, which we store in server.
4. This(server) object has a method named listen, and takes a numeric value which indicates the port number our HTTP server is going to listen.

Now lets analyze the, how requestHandler handling the requests. Whenever a request received, requestHandler function gets triggered and two parameters are passed into it, request and response.

1. response.writeHead() send an HTTP status and content-type in the HTTP response header.
2. response.write() send the text “Hello World” in the HTTP response body.
3. response.end() finish response.

Amit Kumar
amit.kumar@intelligrape.com
in.linkedin.com/in/amitkumar0110
twitter.com/amit_kumar0110
More Blogs by Me

FOUND THIS USEFUL? SHARE IT

Leave a comment -