javascript / intermediate
Snippet
Minimalist Route Dispatching with Node.js HTTP Module
Node.js allows building basic Web application frameworks using the native `node:http` module. Mapping method-path strings to handler functions in a `Map` creates a lightweight, deterministic request router without external libraries.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import http from 'node:http';const routes = new Map([['GET /api/status', (req, res) => res.end(JSON.stringify({ status: 'ok' }))],['POST /api/echo', (req, res) => res.end('Echo response')]]);const server = http.createServer((req, res) => {const routeKey = `${req.method} ${req.url}`;const handler = routes.get(routeKey);if (!handler) {res.statusCode = 404;return res.end(JSON.stringify({ error: 'Route not found' }));}res.setHeader('Content-Type', 'application/json');handler(req, res);});server.listen(3000);
nodejs
Breakdown
1
const routes = new Map([
Creates a Map storing HTTP method and path combinations linked to handler functions.
2
const handler = routes.get(routeKey);
Retrieves the corresponding request handler based on the incoming request method and URL.
3
if (!handler) {
Evaluates control flow when no match is found, returning a 404 status response.