Wednesday, August 12, 2015

How to create a simple Http Server in NodeJs

Node.js is an open source, cross-platform runtime environment for server-side and networking applications. Node.js applications are written in JavaScript and can be run within the Node.js runtime on OS X, Microsoft Windows, Linux.

Node.js uses the Google V8 JavaScript engine to execute code, and a large percentage of the basic modules are written in JavaScript. Node.js contains a built-in library to allow applications to act as a Web server without software such as Apache HTTP Server or IIS.
In this post I will show you how to create a simple Http Server using node.js Before diving into code let us first install node.js from following link.

https://nodejs.org/

Once the node.js installed.Open the terminal window and type following command.

node –version

image

If you see similar output then node.js is installed on your machine.

Open any text editor and paste following code into it and save it as Sever.js.

 

var http = require("http");

function requestHandler(req, res) {

	res.writeHead(200, { 'Content-Type': 'text/html' });
	res.write("Hello world");
	//end the response
	res.end();

}
//Create http server
var server = http.createServer(requestHandler);
server.listen(8000, function () {
	console.log("Server is up and running");
})

open command prompt and type following command.

node Server.js

image