Step-by-Step Guide: Managing Routing in Node.js Without External Libraries
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
-
Create a new directory for your project:
mkdir node-router cd node-router -
Initialize a new Node.js project:
npm init -y
Step 2: Create Basic Project Structure
- 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
-
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; -
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; -
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
-
Create
router.jsin the project root:touch router.js -
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
- 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
-
In your terminal, run the server:
node server.js -
You should see the following output in your terminal:
Server running at http://127.0.0.1:3000/
Step 7: Testing the Routes
- Open your web browser or use a tool like
curlto test the server:- Visit
http://127.0.0.1:3000/to see the "Hello, World!" message. - Visit
http://127.0.0.1:3000/aboutto see the "About Page" message. - Visit any other URL to see the "Not Found" message.
- Visit
Explanation of the Code
-
Route Handlers:
- Each route handler is a function that takes
req(request) andres(response) as arguments and sends an appropriate response.
- Each route handler is a function that takes
-
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
routerfunction checks the request URL and delegates it to the appropriate handler or returns a 404 handler if the route doesn't exist.
- In
-
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
routerfunction defined inrouter.js.
- This creates an HTTP server and delegates the routing logic to the
- In
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.