Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to create server instance in Node.js

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 509
    Comment on it

    Here we will learn how to create a server instance in node.js. First of all we will have to check if the node.js is properly setup in our local machine. Let us create a file with name demo.js and write the below code in the file:

    console.log(Testing the nodejs setup);

    Now the code on the terminal we can see will be something like written below:

    username@machinename:~$ cd path of the file
    username@machinename:path of the file$ node demo.js

    if the setup is installed properly you will see the output: Testing the nodejs setup.

    Now to create the instance of the server we will do the following few steps as mentioned bellow:

    1- We will load http module using the require directive as below:

    var http = require(http);

    this http variable is used to store the output returned by the module.

    2- In the next step we will create an http instance that will have a call back function with request and response parameters.

    http.createServer(function(req,resp){
    	resp.writeHead(200,{'Content-Type':'text/plan'});
    	resp.end("Hello World Today is Sunny day..!!");
    }).listen(8081);
    console.log('Server is listening on port 8081');

    In the above code we have used the createServer function to create the server instance and use a listen method that will listen all the requests at the port 8081 from the client. If we write the code in the 1 and 2 step in a demo.js file and run the below command on the terminal

    username@machinename:~$ cd path of the file
    username@machinename:path of the file$ node demo.js

    we will see the following output:

    on the browser: Hello World Today is Sunny day..!!

    on the terminal: Server is listening on port 8081

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: