http

import { createServer } from "node:http";

const server = createServer((req, res) => {
  res.writeHead(200, { "Content-Type": "text/plain" });
  res.end("local\n");
});

await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const port = server.address().port;
const res = await fetch(`http://127.0.0.1:${port}/`);
console.log(await res.text());
await new Promise((resolve) => server.close(resolve));

Output:

local

Port zero

Asking for port 0 lets the runtime choose a free port Useful in tests and labs No collision with another process

Headers

Set Content-Type explicitly Guessing from file names is how a download becomes executable in a browser

Body size

A request body has no trustworthy size until you enforce one Set a limit before parsing An unbounded body is a memory denial of service

Closing

server.close() waits for active connections A script that exits without it leaves handles open Tests hang for that reason

Next

Waiting in 08 async

Posted