a blog for those who code

Tuesday 24 June 2014

Create Http server for running nodejs

There are many ways you can create a http-server for running your node.js application. The simplest which I feel is to use http-server command.In this post I will explain you how to create Http server for running nodejs application.

Open Command Prompt and navigate to the directory where you have installed nodejs. In that directory you have to run the following command -

npm install http-server -g

It will install a http-server for you. You can check all the options available using http-server --help. To start the http-server you just have to type http-server in your command prompt. If you use "http-server -o" it will open the browser after starting the server.

Instead of this we can also write a simple node.js application to start the server.

var http = require('http');
var requestListener = function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/plain'});
  response.end('Hello You\n');
}

var server = http.createServer(requestListener);
server.listen(8080); // The port where you want to start with.

Hope this helps. If you have any questions or suggestions, please do comment. Please Like and Share the Blog, if you find it interesting and helpful.

No comments:

Post a Comment