Working with HTTP Server
1. Creating HTTP Server (http.createServer)
Example: Minimal server
import http from "node:http";
const server = http.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ ok: true }));
});
server.listen(3000, () => console.log("ready"));
2. Listening on Port (server.listen)
| Form | Effect |
server.listen(3000) | Bind to port |
server.listen(3000, "0.0.0.0") | All interfaces |
server.listen({ port: 0 }) | Random free port |
server.listen("/tmp/app.sock") | Unix socket |
3. Handling Requests
| Property | Description |
req.method | HTTP verb |
req.url | Path + query |
req.headers | Lowercased object |
req.socket.remoteAddress | Client IP |
req.httpVersion | 1.1 / 2.0 |
4. Reading Request Data
Example
let body = "";
req.setEncoding("utf8");
for await (const chunk of req) body += chunk;
5. Handling Request Body
| Content-Type | Parser |
application/json | JSON.parse |
application/x-www-form-urlencoded | new URLSearchParams |
multipart/form-data | busboy / formidable |
text/* | Raw string |
6. Using URL Module for Parsing
Example
const url = new URL(req.url, `http://${req.headers.host}`);
const id = url.searchParams.get("id");
7. Implementing Routing
Example: Manual router
function route(req, res) {
const url = new URL(req.url, "http://x");
if (req.method === "GET" && url.pathname === "/users") return listUsers(res);
if (req.method === "POST" && url.pathname === "/users") return createUser(req, res);
res.writeHead(404).end("not found");
}
Note: For real apps prefer Express, Fastify, Koa, or Hono.
8. Sending Responses
| Method | Use |
res.write(chunk) | Send body chunk |
res.end(data?) | Finish |
res.writeHead(status, headers) | Status + headers in one call |
res.flushHeaders() | Send headers immediately (streaming) |
| API | Use |
res.setHeader(name, value) | Single header |
res.getHeader(name) | Read |
res.removeHeader(name) | Delete |
res.headersSent | Boolean |
10. Setting Status Codes (res.statusCode)
| Code | Meaning |
| 200/201/204 | OK / Created / No Content |
| 301/302/304 | Moved / Found / Not Modified |
| 400/401/403/404 | Bad / Unauthorized / Forbidden / Not Found |
| 409/422/429 | Conflict / Unprocessable / Too Many |
| 500/502/503/504 | Server / Bad Gateway / Unavailable / Timeout |
11. Serving Static Files
Example: Stream file
import { createReadStream } from "node:fs";
import { pipeline } from "node:stream/promises";
res.setHeader("Content-Type", "image/png");
await pipeline(createReadStream("./logo.png"), res);
Warning: Always validate paths to prevent path-traversal (..).
12. Closing Server (server.close)
| Method | Behavior |
server.close(cb) | Stop new conns; finish existing |
server.closeAllConnections() | Force-close v18.2+ |
server.closeIdleConnections() | Drop idle keep-alive sockets |
13. Handling Server Errors
| Event | Cause |
error | Bind failure (e.g. EADDRINUSE) |
clientError | Bad client request |
request | Each incoming request |