Create Basic HTTP Server with Node.js

10 / May / 2013 by Amit Kumar 1 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:

[js]
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.”);
[/js]

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

[bash]
node server.js
[/bash]

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

comments (1 “Create Basic HTTP Server with Node.js”)

  1. Viren Rakholiya

    Respected sir,
    I have seen your blog on node JS server. Can help? I want to get data from Arduino and use that data on my localserver using node JS. for that, I want to make Node JS script. can u send some reference or source code. reply as soon as possible. Im from Nirma university, Ahmedabad. Im doing IT engineering.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *