Blog / Node JS

How to Create a NodeJS Router Without Using a Framework

This is a very basic example for demonstrates the core concepts of routing in Node.js. In a real-world application, the router would likely be more complex, with multiple routes and more functionality. But this example should provide a good starting point for understanding how routing works in Node.js.

A router in Node.js is a way to handle and direct incoming HTTP requests to the appropriate function or endpoint. It can be implemented using the built-in "http" module, without the need for any additional frameworks.

Here is an example of a simple router in Node.js:

const http = require('http');

const server = http.createServer((req, res) => {
  switch (req.url) {
    case '/':
      res.end('Welcome to the home page!');
      break;
    case '/about':
      res.end('Learn more about us!');
      break;
    default:
      res.end('404 Page Not Found');
  }
});

server.listen(3000);
console.log('Server listening on port 3000');

in this example, we are using the built-in "http" module to create a server that listens for incoming requests. When a request is received, the server uses a switch statement to determine the URL of the request and directs it to the appropriate endpoint. The endpoints in this example are the home page and an "about" page, but this can be expanded to include any number of routes.

Once the server is created, it is set to listen on port 3000 using the "listen" method. And then a message is logged to the console to indicate that the server is running.