Home

Step-by-Step Guide: Managing Routing in Node.js Without External Libraries

36 views

Managing routing in a Node.js application using the built-in http module can become complex as your application grows. For a more organized and scalable approach, it's important to structure your routing logic effectively. Here's a step-by-step guide to managing routing without using external libraries like Express.js:

Step 1: Setup Project Directory

  1. Create a new directory for your project:

    mkdir node-router
    cd node-router
    
  2. Initialize a new Node.js project:

    npm init -y
    

Step 2: Create Basic Project Structure

  1. Create the following files and directories:
    touch server.js
    mkdir routes
    cd routes
    touch index.js
    touch about.js
    touch notFound.js
    

Step 3: Define Routes

  1. In routes/index.js:

    const index = (req, res) => {
      res.statusCode = 200;
      res.setHeader('Content-Type', 'text/plain');
      res.end('Hello, World!\n');
    };
    
    module.exports = index;
    
  2. In routes/about.js:

    const about = (req, res) => {
      res.statusCode = 200;
      res.setHeader('Content-Type', 'text/plain');
      res.end('About Page\n');
    };
    
    module.exports = about;
    
  3. In routes/notFound.js:

    const notFound = (req, res) => {
      res.statusCode = 404;
      res.setHeader('Content-Type', 'text/plain');
      res.end('Not Found\n');
    };
    
    module.exports = notFound;
    

Step 4: Implement Router Logic

  1. Create router.js in the project root:

    touch router.js
    
  2. In router.js:

    const fs = require('fs');
    const path = require('path');
    
    const routes = {
      '/': require('./routes/index'),
      '/about': require('./routes/about')
    };
    
    const router = (req, res) => {
      const handler = routes[req.url] || require('./routes/notFound');
      handler(req, res);
    };
    
    module.exports = router;
    

Step 5: Set Up the HTTP Server

  1. In server.js:
    const http = require('http');
    const router = require('./router');
    
    const hostname = '127.0.0.1';
    const port = 3000;
    
    const server = http.createServer((req, res) => {
      router(req, res);
    });
    
    server.listen(port, hostname, () => {
      console.log(`Server running at http://${hostname}:${port}/`);
    });
    

Step 6: Running the Server

  1. In your terminal, run the server:

    node server.js
    
  2. You should see the following output in your terminal:

    Server running at http://127.0.0.1:3000/
    

Step 7: Testing the Routes

  1. Open your web browser or use a tool like curl to test the server:
    • Visit http://127.0.0.1:3000/ to see the "Hello, World!" message.
    • Visit http://127.0.0.1:3000/about to see the "About Page" message.
    • Visit any other URL to see the "Not Found" message.

Explanation of the Code

  1. Route Handlers:

    • Each route handler is a function that takes req (request) and res (response) as arguments and sends an appropriate response.
  2. Router Logic:

    • In router.js:
      const routes = {
        '/': require('./routes/index'),
        '/about': require('./routes/about')
      };
      
      const router = (req, res) => {
        const handler = routes[req.url] || require('./routes/notFound');
        handler(req, res);
      };
      
      module.exports = router;
      
      • This object maps route paths to their respective handler functions.
      • The router function checks the request URL and delegates it to the appropriate handler or returns a 404 handler if the route doesn't exist.
  3. HTTP Server:

    • In server.js:
      const http = require('http');
      const router = require('./router');
      
      const hostname = '127.0.0.1';
      const port = 3000;
      
      const server = http.createServer((req, res) => {
        router(req, res);
      });
      
      server.listen(port, hostname, () => {
        console.log(`Server running at http://${hostname}:${port}/`);
      });
      
      • This creates an HTTP server and delegates the routing logic to the router function defined in router.js.

By following this approach, you have modularized your routing logic, making it easier to manage, scale, and maintain. This is a highly simplified version of what frameworks like Express.js do under the hood, but it provides a solid foundation for understanding and building upon.