IF Commons GitHub

serve

Written to: 1 requirement: 1 proved, 0 partly, 0 failing, 0 with no test recorded. 0001-net FR-002

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();

Source: commons/net/src/serve.ts

3 of 7 exports are imported by a test of the run. A test that imports an export may not call it or check what it returns.

tcp.NetAddrtypeno test imports it
type NetAddr = { readonly hostname: string; readonly port: number };

Where the server listens, or where a request came from.

servefunction
function 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.

Imported by 26 tests of the run (26 passed, 0 failed): the library's results

NetAddrtypeno test imports it
type NetAddr = { readonly hostname: string; readonly port: number };

Where the server listens, or where a request came from.

Servertype
type 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.

Imported by 3 tests of the run (3 passed, 0 failed): the library's results

ServeHandlertype
type ServeHandler = (request: Request, info: ServeInfo) => Response | Promise<Response>;

A function from a request to its response.

Imported by 13 tests of the run (13 passed, 0 failed): the library's results

ServeInfotypeno test imports it
type ServeInfo = { readonly remoteAddr: NetAddr };

What a handler knows of a request besides the request itself.

ServeOptionstypeno test imports it
type 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.

Titles, headings, exports, tables, columns and requirements. Esc closes.