Node Js : Creating a HTTP server

Node.js is shipped with several core modules out of the box, one of which the http module makes it simple to create an http server. Lets create a file called webServer.js.


var http = require('http');

http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(8080);

console.log('Server running on port 8080.');

As you can see, we need the build in http module, the createServer method of which will create a server. Like most Node.js functions, createServer() takes a callback function as an argument. This callback function is executed each time the server receives a new request. The request object contains information regarding the client’s request, such as the URL, HTTP headers, and much more. Similarly, the response object is used to return data back to the client. The create server listen on port 8080. We can also provide the hostname as a second paramenter to the listen. Lets run it

webserver_basic_running

webserver_basic_result1

Lets modify our code a bit


var http = require('http');

http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write("Heading of page\n");
res.end('Hello World\n');
res.write("Footer of page\n");
}).listen(8080);

console.log('Server running on port 8080.');

Notice that we are writing in the response now. Rerun the file again. Output:

webserver_basic_result2

As you can see, after we call the end in response object we cant write on it anymore.
Lets modify it bit more


var http = require('http');

http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
setInterval(function(){
res.write(new Date()+"\n");
},1000);
}).listen(8080);

console.log('Server running on port 8080.');

Above , we are not doing any res.end() and infact writing on response every 1 sec. Output:

webserver_basic_result3

It took roughlt 15-20 sec to load the page first with 15-20 lines and then continuosly added lines after 1 sec. This is because the browser waited for the server to end the response first, since the response was written every 1 sec. So node can create a connection and keep it open and keep the data sending.

Lets modify our server code in different files. server.js


var http = require('http');

function start(port) {
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
      res.end("Hello World");  
  }).listen(port);
console.log("Server has started listening on port " + port);
}

exports.start = start;

app.js:


var server = require("./server");

server.start(8080);

If we start the app.js , and hit localhost:8080, the result will be same.

So far whatever url we hit the response will be the same Hello world. Lets add few routing function that responds dfferently to differnet urls

Lets write a requesthandler.js that sets different response.


function home(req,res) {
console.log("Request handler 'home' was called.");
res.writeHead(200, {"Content-Type": "text/plain"});
res.write("home page");
res.end();
}

function search(req,res) {
console.log("Request handler 'search' was called.");
res.writeHead(200, {"Content-Type": "text/plain"});
res.write("search page");
res.end();
}

exports.home = home;
exports.search = search;

router.js – a function to take an array of routes that have been wired up (“handle”), that current request’s path (“pathname”), and the response to manipulate, and attempt to match and call the correct function else return a 404:


function route(handle, pathname,req,res) {
if (typeof handle[pathname] === 'function') {
handle[pathname](req,res);
} else {
console.log("No request handler found for " + pathname);
res.writeHead(404, {"Content-Type": "text/plain"});
res.write("404 Not found");
res.end();
}
}

exports.route = route;

modifyinf server.js to pass the requrest to the router:


var http = require('http');
var    url = require("url");

function start(route, handle,port) {
http.createServer(function (req, res) {
var pathname = url.parse(req.url).pathname;
route(handle, pathname, req, res);
}).listen(port);
console.log("Server has started listening on port " + port);
}

exports.start = start;

app.js to start:


var server = require("./server"),
router = require("./router"),
requestHandlers = require("./requestHandler");

var handle = {}
handle["/home"] = requestHandlers.home;
handle["/search"] = requestHandlers.search;

server.start(router.route, handle, 8080);

Output:

webserver_basic_result_routing

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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

%d bloggers like this: