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.
// 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
.
Open your browser while the server application is running and head over to http://localhost:5000/. You must see the "Hello World" message!