HTTP Module

One of the most powerful modules in Node is the HTTP module. It can be used for building networking applications. For example, we can create an HTTP server that listens to HTTP requests on a given port.

import http from "http";

const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader("Content-Type", "text/plain");
  res.end("Hello World\n");
});

server.listen(port, () => {
  console.log(`Server running at http://localhost:${port}/`);
});

As you run index.js you must see the following message printed in the terminal:

Server running at http://localhost:3000/

Note the application is running! To stop it, you must halt the process by pressing Ctrl + C.

Open your browser while the server application is running and head over to http://localhost:3000/. You must see the "Hello World" message!