Beginner LevelNode JS
How do you build a HTTP server using the native node:http module?
❓ Interview Prompt: Explain `node:http` module, `http.createServer()`, IncomingMessage (req), ServerResponse (res), status codes, and routing.
The native 'node:http' module provides low-level HTTP server and client capabilities without third-party frameworks:
•
'http.createServer((req, res) => ...)': Instantiates an HTTP server handling incoming 'IncomingMessage' streams and responding via 'ServerResponse'.
Code Implementation Example
javascript
import http from 'node:http';
const server = http.createServer((req, res) => {
if (req.method === 'GET' && req.url === '/health') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ status: 'OK', uptime: process.uptime() }));
return;
}
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
});
server.listen(3000, () => console.log('HTTP Server listening on port 3000'));💡Creating a HTTP server using the native node:http module.
🎯 Interview Key Takeaway
Understand node:http createServer mechanics as it forms the underlying server implementation for frameworks like Express and Fastify.
#http#createServer#IncomingMessage#ServerResponse#Beginner
Back to all Node JS Questions→