Running a simple server using Node.Js : Simplest Node Application

First of all to follow this simple tutorial you should have installed Node.Js .

Lets create a simple HTTP server with Node.Js
  • Open a text editor as your preference
  • Insert this code snippet and save it as hello.js (as a JavaScript File)

    
    var http=require('http'); // add the http module
    
    
    var myServer=http.createServer(function(request,response){
    
     response.writeHead(200,{"Content-Type":"text/plain"});
    
     response.write("Hello World"); //writing a response to String
    
     response.end();
    
    });//create server
    
    myServer.listen(3000); //assign a port to listen
    
    
    
    // Console will print the message
    
    console.log('listening at port 3000');
    
    
    

  • Open a Node.Js command prompt and go to directory where you saved your "hello.js" file
  • Run your simple server with "node hello.js" command.
  • You will see a message "listening on port 3000" if there is nothing wrong
  • Finally open browser and test your HTTP server with entering URL "http://localhost:3000/"

No comments:

Post a Comment