Friday 16 January 2015

How to start nodejs server and set listening to a port.


node js nodejs


Here is a program server.js that one server object which listens through port 3000 on localhost.







/* require function includes http module  */

var http = require('http');




/* res.writeHead writes the meta content type and res.end writes  body text that is to be displayed in the page*/

var handleRequest = function (req,res) {
    res.writeHead(200,{'Content-Type':'text/plain'});
    res.end('Message : Server localhost listening to port 3000\n');
};

/*Function createServer  of http object is called that creates the server object server. */

var server = http.createServer(handleRequest);

/* server starts listening to port 3000 */

server.listen(3000,'localhost');

Save this file as server.js.

Now go to the terminal and cd to the directory where server.js is saved.
Type the command node server or node server.js.

Node starts listening on port 3000.

Now go to your web browser and enter url http://localhost:3000.

You browser should display  


Message : Server localhost listening to port 3000

No comments: