iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

http

Node ships an http module — servers and clients without any dependencies. Express/Fastify build on top, but the raw API is small enough to use directly for small services, proxies, and health checks.

Server + client with raw http

EXAMPLE
import http from 'node:http';
import https from 'node:https';
import { URL } from 'node:url';

// 1) A minimal server
const server = http.createServer(async (req, res) => {
    const url = new URL(req.url, `http://${req.headers.host}`);

    if (req.method === 'GET' && url.pathname === '/health') {
        res.writeHead(200, { 'content-type': 'application/json' });
        return res.end(JSON.stringify({ ok: true, uptime: process.uptime() }));
    }

    if (req.method === 'POST' && url.pathname === '/echo') {
        const chunks = [];
        for await (const c of req) chunks.push(c);
        const body = Buffer.concat(chunks).toString('utf8');
        res.writeHead(200, { 'content-type': 'text/plain' });
        return res.end(body);
    }

    res.writeHead(404, { 'content-type': 'text/plain' });
    res.end('Not Found');
});

server.listen(3000, () => console.log('on :3000'));

// 2) Graceful shutdown
const shutdown = () => {
    server.close((err) => process.exit(err ? 1 : 0));
    setTimeout(() => process.exit(1), 10_000).unref(); // hard kill if stuck
};
process.on('SIGTERM', shutdown);
process.on('SIGINT',  shutdown);

// 3) Built-in client — prefer global fetch in Node 18+
const res = await fetch('https://api.github.com/users/octocat', {
    headers: { 'user-agent': 'demo' },
});
const json = await res.json();
console.log(json.name);

// 4) Streaming response — never buffer giant payloads
import { createReadStream } from 'node:fs';
const app = http.createServer((req, res) => {
    res.writeHead(200, { 'content-type': 'video/mp4' });
    createReadStream('./big.mp4').pipe(res);
});

// 5) Keep-alive agent for outbound clients
import { Agent } from 'node:https';
const agent = new Agent({ keepAlive: true, maxSockets: 50 });
await fetch('https://api.example.com/x', { agent });

Why it matters

For real services use Express/Fastify/Hono — but knowing the raw http module pays off when you debug, build proxies, or write a sidecar. Everything sits on streams and headers.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
import http from 'node:http';
http.createServer((req, res) => {
    res.end('Hello!');
}).listen(3000);
Try it Yourself »

Discussion

Loading…