function bindServerToPort
bindServerToPort(
server: HTTPServer,
config: { port: number; portExplicit?: boolean; },
retryDelayMs?: number
): Promise<HTTPServer>

Binds an HTTPServer to config.port (default 1234).

  • Auto-port (portExplicit false): increments on EADDRINUSE until a free port is found.
  • Explicit port (portExplicit true): retries up to EXPLICIT_PORT_RETRIES times on EADDRINUSE to recover from transient TOCTOU races, then throws if still occupied. Uses try-catch on the actual listen() call — never check-then-listen (TOCTOU).
import type { HTTPServer } from '../web/index.ts';

// Defined, not invoked: binds a real port.
async function bind(server: HTTPServer, config: { port: number; portExplicit?: boolean }) {
  await bindServerToPort(server, config);
  return config.port; // updated in place to the port actually bound
}

Parameters

server: HTTPServer
config: { port: number; portExplicit?: boolean; }
optional
retryDelayMs: number = EXPLICIT_PORT_RETRY_DELAY_MS

Return Type

Promise<HTTPServer>

Usage

import { bindServerToPort } from "lib/setup/bind-server-to-port.ts";