Creating a Node Program

  1. Create a JavaScript file and name it hello.js . This can be done using the options in the File tab.
  2. Load the built-in http module by using the “require” directive and passing a constant variable ( http ) to it:
    const http = require ('http');
  3. Declare and initialize the hostname and port as constant variables using the following code:
    const hostname = '127.0.0.1';
    const port = 8000;
  4. Create the server using the createServer method and pass req and res , which denote a request to and a response from the server, respectively:
    const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Hello World\n');
    });

    This created server sends the following response to the browser: statusCode : 200 , the Content-Type header in plain text, and a string, Hello World.
  5. Have the server listen to localhost on port 8000 using the following command:
    server.listen(port, hostname, () => {
    console.log ('Server running at http://${hostname}:${port}/'); });
    Run the server using the following command prompt, as shown in the following screenshot:
    node hello.js