diff --git a/net/get_available_port.ts b/net/get_available_port.ts index 7180e66c5..f357822d5 100644 --- a/net/get_available_port.ts +++ b/net/get_available_port.ts @@ -17,16 +17,40 @@ export interface GetAvailablePortOptions { /** * Returns an available network port. * + * > [!IMPORTANT] + * > In most cases, this function is not needed. Do not use it for trivial uses + * > such as when using {@linkcode Deno.serve} or {@linkcode Deno.listen} + * > directly. Instead, set the `port` option to `0` to automatically use an + * > available port, then get the assigned port from the function's return + * > object (see "Recommended Usage" example). + * * @param options Options for getting an available port. * @returns An available network port. * - * @example Usage + * @example Recommended Usage + * + * Bad: * ```ts no-eval no-assert * import { getAvailablePort } from "@std/net/get-available-port"; * * const port = getAvailablePort(); * Deno.serve({ port }, () => new Response("Hello, world!")); * ``` + * + * Good: + * ```ts no-eval no-assert + * const { port } = Deno.serve({ port: 0 }, () => new Response("Hello, world!")).addr; + * ``` + * + * Good: + * ```ts no-eval no-assert + * import { getAvailablePort } from "@std/net/get-available-port"; + * + * const command = new Deno.Command(Deno.execPath(), { + * args: ["test.ts", "--port", getAvailablePort().toString()], + * }); + * // ... + * ``` */ export function getAvailablePort(options?: GetAvailablePortOptions): number { if (options?.preferredPort) { diff --git a/net/mod.ts b/net/mod.ts index f86259c23..009017d44 100644 --- a/net/mod.ts +++ b/net/mod.ts @@ -8,7 +8,11 @@ * * console.log(`My network IP address is ${getNetworkAddress()}`); * - * Deno.serve({ port: getAvailablePort() }, () => new Response("Hello, world!")); + * const command = new Deno.Command(Deno.execPath(), { + * args: ["test.ts", "--port", getAvailablePort().toString()], + * }); + * + * // ... * ``` * * @module