In this post we will discuss about the simple program in node.js , in order to understand the basics of node.js programming. We will understand this with the help of an example in node.js. We will go step by step. First in order to execute the node.js program you have to install node.js.  After that follow the below steps:

  • Open a new folder
  • npm init
  • First step to create package.json file
  • It will be created in the new folder.

Create a new file index.js :

In this example we will use http to create server and then client will access it using browser using node.js.

  • const http = require(‘http’); // http module that is used to create server
  • const hostname = ‘127.0.0.1’;
    const port = 5000;
  • const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader(‘Content-Type’, ‘text/plain’);
    res.end(‘Hello World\n’);
    });
  • server.listen(port, hostname, () => {

}

Run node.js Program:

  • Node index.js  // on the command prompt write node inxex.js

 

Now open the browser on 5000 port to check the result:

To use the application, open http://localhost:5000 in a browser to see the words Hello World.

 

121total visits,2visits today