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 build an HTTP server that listens to HTTP requests on a given port.

// index.js file
const http = require("http");

const PORT = 5000;
const server = http.createServer(routes);

function routes(request, response) {
  if (request.url === "/") {
    response.write("Hello world!");
    response.end(); // Don't forget this!
  }
}

server.listen(PORT);

console.log(`The server is listening on port ${PORT}`);

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

The server is listening on port 5000

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

While the server application is running, open your browser and head over to http://localhost:5000/. You must see the "Hello World" message!

A note on PORT

In computer networking, a port is a communication endpoint.

  • Port numbers start from 0.
  • The numbers 0 to 1024 are reserved for privileged services (used by the operating system, etc.).
  • For local development, you can safely use any number \(\ge 3000\).

It is beyond the scope of this course to explore what a port is and how it operates. An interested reader is referred to the Wikipedia entry "Port (computer networking)".