Node.js
HTTP Server
Build an HTTP server with the http module and routing.
By EZ4Code Team
httpserverrouting
Code
import { createServer } from "http";
const server = createServer(async (req, res) => {
const url = new URL(req.url, "http://localhost");
res.setHeader("Content-Type", "application/json");
if (req.method === "GET" && url.pathname === "/api/users") {
res.end(JSON.stringify([{ id: 1, name: "Alice" }]));
return;
}
if (req.method === "POST" && url.pathname === "/api/users") {
const body = await readBody(req);
res.statusCode = 201;
res.end(JSON.stringify({ created: body }));
return;
}
res.statusCode = 404;
res.end(JSON.stringify({ error: "Not found" }));
});
function readBody(req) {
return new Promise(resolve => {
let data = "";
req.on("data", chunk => (data += chunk));
req.on("end", () => resolve(JSON.parse(data || "{}")));
});
}
server.listen(3000, () => console.log("listening on :3000"));Explanation
createServer returns an HTTP server that invokes a callback for each request, with req and res streams for reading the body and writing the response. The URL constructor parses the request URL for routing, and a helper buffer reads the request body. For production apps, prefer a framework like Express or Fastify.
More Node.js Snippets
fs Module
Read, write, and watch files with promises and callbacks.
Streams
Pipe, transform, and consume streams efficiently.
EventEmitter
Emit and listen for custom events.
path Module
Join, resolve, and parse file paths cross-platform.
Buffers
Work with binary data using Buffer and TypedArrays.
Child Process
Spawn, exec, and fork external processes.