mirror of
https://github.com/denoland/std.git
synced 2024-11-22 04:59:05 +00:00
6c615c976d
* feat(net): add preferredPort option to getAvailablePort * Apply suggestions from code review --------- Co-authored-by: Asher Gomez <ashersaupingomez@gmail.com>
42 lines
1.2 KiB
TypeScript
42 lines
1.2 KiB
TypeScript
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
|
|
|
/** Options for {@linkcode getAvailablePort}. */
|
|
export interface GetAvailablePortOptions {
|
|
/**
|
|
* A port to check availability of first. If the port isn't available, fall
|
|
* back to another port.
|
|
*/
|
|
preferredPort?: number;
|
|
}
|
|
|
|
/**
|
|
* Returns an available network port.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* import { getAvailablePort } from "https://deno.land/std@$STD_VERSION/net/get_available_port.ts";
|
|
*
|
|
* const port = getAvailablePort();
|
|
* Deno.serve({ port }, () => new Response("Hello, world!"));
|
|
* ```
|
|
*/
|
|
export function getAvailablePort(options?: GetAvailablePortOptions): number {
|
|
if (options?.preferredPort) {
|
|
try {
|
|
// Check if the preferred port is available
|
|
const listener = Deno.listen({ port: options.preferredPort });
|
|
listener.close();
|
|
return (listener.addr as Deno.NetAddr).port;
|
|
} catch (e) {
|
|
// If the preferred port is not available, fall through and find an available port
|
|
if (!(e instanceof Deno.errors.AddrInUse)) {
|
|
throw e;
|
|
}
|
|
}
|
|
}
|
|
|
|
const listener = Deno.listen({ port: 0 });
|
|
listener.close();
|
|
return (listener.addr as Deno.NetAddr).port;
|
|
}
|