Monday, July 4, 2016

A Simple Localhost Server

Supports:
Windows and Mac OS

Step 1:
Download and install Nodejs.

Step 2:
Write the Javascript shown below in your favorite editor. I recommend Sublime Text. Save the file in a  folder where your javascript/html files will reside. Call the file server.js.

/**
 *A simple localhost web server.
 */
var http = require('http');
var fs = require('fs');
var url = require('url');


// Create a server
http.createServer( function (request, response) { 
   // Parse the request containing file name
   var pathname = url.parse(request.url).pathname;
  
   // Print the name of the file for which request is made.
   console.log("Request for " + pathname + " received.");
  
   // Read the requested file content from file system
   fs.readFile(pathname.substr(1), function (err, data) {
      if (err) {
         console.log(err);
         // HTTP Status: 404 : NOT FOUND
         // Content Type: text/plain
         response.writeHead(404, {'Content-Type': 'text/html'});
      }else{   
         //Page found     
         // HTTP Status: 200 : OK
         // Content Type: text/plain
         response.writeHead(200, {'Content-Type': 'text/html'});   
        
         // Write the content of the file to response body
         response.write(data.toString());       
      }
      // Send the response body
      response.end();
   });  
}).listen(8081);

// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');

Step 3:
Go to your command prompt.
Windows: Start > run> cmd
Mac: Finder > Applications > Utilities > Terminal

Step 4:
Go to that directory and run:
node server.js 

Step 5:
If you haven't put any other files in this directory, put a simple index.html file with some text in it just to verify that this works. 

Step 6:
Launch your favorite browser and go to: http://127.0.0.1:8081/index.html

No comments:

Post a Comment