Saturday, October 01, 2016

Run a server from Node.js

Step 1: Download and install Node.js from

Step 2: Launch node from command prompt and verify it has installed correctly

Step 3: Create a new file server.js as follows:

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

http.createServer( function (request, response)
   var pathname = url.parse(request.url).pathname;
   fs.readFile(pathname.substr(1), function (err, data)
      if (err)
         response.writeHead(404, {'Content-Type': 'text/html'});
         response.writeHead(200, {'Content-Type': 'text/html'});   

console.log('Server running at');

Step 4: Open command prompt and change to directory where you have saved server.js

Step 5: Run node server.js from command prompt

Step 6: Now open browser and go to localhost:8844 and it will open your homepage