tcp.NetAddrtypeno test imports ittype NetAddr = { readonly hostname: string; readonly port: number };Where the server listens, or where a request came from.
An HTTP server whose handler takes a web Request and gives a web Response on node:http, so the same handler runs on Bun and Node (commons 0001-net FR-002). Request bodies and response bodies stream; a client that goes away aborts request.signal. serve returns a promise, settled once the port is bound, so addr is known.
import { serve } from "./serve.ts";
const server = await serve({ port: 0, hostname: "127.0.0.1" }, (req) => new Response(`you asked for ${new URL(req.url).pathname}`));
const text = await (await fetch(`http://127.0.0.1:${server.addr.port}/x`)).text(); // "you asked for /x"
await server.shutdown();tcp.NetAddrtypeno test imports ittype NetAddr = { readonly hostname: string; readonly port: number };Where the server listens, or where a request came from.
servefunctionfunction serve(options: ServeOptions, handler: ServeHandler): Promise<Server>A server that answers each request with what handler gives, once its port is bound. AddrInUse where the port is taken.
NetAddrtypeno test imports ittype NetAddr = { readonly hostname: string; readonly port: number };Where the server listens, or where a request came from.
Servertypetype Server = {
/** Where it listens. */
readonly addr: NetAddr;
/** Settles when it has shut down. */
readonly finished: Promise<void>;
/** Stop listening and close every connection; settles when it has shut down. */
shutdown(): Promise<void>;
};A running server.
ServeHandlertypetype ServeHandler = (request: Request, info: ServeInfo) => Response | Promise<Response>;A function from a request to its response.
ServeInfotypeno test imports ittype ServeInfo = { readonly remoteAddr: NetAddr };What a handler knows of a request besides the request itself.
ServeOptionstypeno test imports ittype ServeOptions = {
/** The port; 0 (the default) asks the system for a free one. */
readonly port?: number;
/**… (458 characters)type ServeOptions = {
/** The port; 0 (the default) asks the system for a free one. */
readonly port?: number;
/** The address to bind; `127.0.0.1` by default, never every interface unless asked. */
readonly hostname?: string;
/** Aborting it shuts the server down. */
readonly signal?: AbortSignal;
/** The response where the handler throws (a plain 500 by default). */
readonly onError?: (error: unknown) => Response | Promise<Response>;
};Where and how to listen.