Performance: Routing requests manually
This affects server response time and how quickly the server can handle incoming HTTP requests.
Jump into concepts and practice - no test required
const http = require('http'); const routes = { '/': (res) => res.end('Home Page'), '/about': (res) => res.end('About Page'), '/contact': (res) => res.end('Contact Page') }; const server = http.createServer((req, res) => { const handler = routes[req.url]; if (handler) { handler(res); } else { res.statusCode = 404; res.end('Not Found'); } }); server.listen(3000);
const http = require('http'); const server = http.createServer((req, res) => { if (req.url === '/') { res.end('Home Page'); } else if (req.url === '/about') { res.end('About Page'); } else if (req.url === '/contact') { res.end('Contact Page'); } else { res.statusCode = 404; res.end('Not Found'); } }); server.listen(3000);
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual if-else routing | N/A (server-side) | N/A | N/A | [X] Bad |
| Object lookup routing | N/A (server-side) | N/A | N/A | [OK] Good |
req.url in a Node.js server without frameworks?req.urlreq.url contains the path requested by the client, like '/home' or '/about'.req.urlreq.url, the server can decide which content or response to send back.res.writeHead() sets status and headers, res.end() sends the response body.writeHead and end correctly. The second and third options use Express methods, not native Node.js. res.write(200, 'Hello'); is invalid syntax./hello?
const http = require('http');
const server = http.createServer((req, res) => {
if (req.url === '/hello') {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World');
} else {
res.writeHead(404);
res.end('Not Found');
}
});
server.listen(3000);req.url === '/hello'. If true, it sends 'Hello World' with status 200.const http = require('http');
const server = http.createServer((req, res) => {
if (req.url = '/test') {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Test page');
} else {
res.writeHead(404);
res.end('Page not found');
}
});
server.listen(3000);req.url = '/test', which assigns instead of compares. This always evaluates to true.req.url === '/test' to compare values properly./data and plain text at /info. Which code snippet correctly implements this?/data, JSON content type 'application/json' is correct. For /info, plain text 'text/plain' is correct.JSON.stringify for JSON data. Other options misuse content types or omit headers.