Raw http Module — The Primitive
Before using Express, understanding Node.js's raw http module reveals what every framework does under the hood. This knowledge is essential for debugging and performance analysis.
HTTP Server from Scratch
import http from 'http';
import { URL } from 'url';
// Every HTTP framework (Express, Fastify) wraps this primitive
const server = http.createServer((req, res) => {
// req: IncomingMessage — readable stream with headers, method, url
// res: ServerResponse — writable stream
const url = new URL(req.url ?? '/', `http://${req.headers.host}`);
const method = req.method?.toUpperCase() ?? 'GET';
// Read request body (it's a stream — must be consumed)
let body = '';
req.on('data', (chunk: Buffer) => { body += chunk.toString(); });
req.on('end', () => {
let parsed: unknown = null;
if (body && req.headers['content-type']?.includes('application/json')) {
try { parsed = JSON.parse(body); } catch { /* ignore invalid JSON */ }
}
// Route manually
if (method === 'GET' && url.pathname === '/health') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ status: 'ok', uptime: process.uptime() }));
return;
}
// 404 fallback
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Not Found' }));
});
});
// Listen
server.listen(3000, () => console.log('Server on http://localhost:3000'));
// Graceful shutdown (handle in-flight requests):
server.close((err) => {
if (err) process.exit(1);
else process.exit(0);
});Tip
Tip
Practice Raw http Module The Primitive in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Every website works on this model
Practice Task
Note
Practice Task — (1) Write a working example of Raw http Module The Primitive from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Raw http Module The Primitive is skipping edge case testing — empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready node code.