2024-01-01 21:11:32 +00:00
|
|
|
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
2023-12-04 04:50:40 +00:00
|
|
|
|
2024-01-11 06:12:47 +00:00
|
|
|
/** 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;
|
|
|
|
}
|
|
|
|
|
2023-12-04 04:50:40 +00:00
|
|
|
/**
|
|
|
|
* 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!"));
|
|
|
|
* ```
|
|
|
|
*/
|
2024-01-11 06:12:47 +00:00
|
|
|
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;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-04 04:50:40 +00:00
|
|
|
const listener = Deno.listen({ port: 0 });
|
|
|
|
listener.close();
|
|
|
|
return (listener.addr as Deno.NetAddr).port;
|
|
|
|
}
|