Saturday, October 01, 2016

Run a server from Node.js

Step 1: Download and install Node.js from https://nodejs.org/en/

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)
      {
         console.log(err);
         response.writeHead(404, {'Content-Type': 'text/html'});
         response.write(err.toString());
      }
      else
      {   
         response.writeHead(200, {'Content-Type': 'text/html'});   
         response.write(data.toString());       
      }
      response.end();
   });  
}).listen(8844);

console.log('Server running at http://127.0.0.1:8844/');

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

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.