UNPKG

1.86 kBTypeScriptView Raw
1import {type ListenOptions} from 'node:net';
2
3export type Options = {
4 /**
5 A preferred port or an iterable of preferred ports to use.
6 */
7 readonly port?: number | Iterable<number>;
8
9 /**
10 Ports that should not be returned.
11
12 You could, for example, pass it the return value of the `portNumbers()` function.
13 */
14 readonly exclude?: Iterable<number>;
15
16 /**
17 The host on which port resolution should be performed. Can be either an IPv4 or IPv6 address.
18
19 By default, it checks availability on all local addresses defined in [OS network interfaces](https://nodejs.org/api/os.html#os_os_networkinterfaces). If this option is set, it will only check the given host.
20 */
21 readonly host?: string;
22} & Omit<ListenOptions, 'port'>;
23
24/**
25Get an available TCP port number.
26
27@returns Port number.
28
29@example
30```
31import getPort from 'get-port';
32
33console.log(await getPort());
34//=> 51402
35
36// Pass in a preferred port
37console.log(await getPort({port: 3000}));
38// Will use 3000 if available, otherwise fall back to a random port
39
40// Pass in an array of preferred ports
41console.log(await getPort({port: [3000, 3001, 3002]}));
42// Will use any element in the preferred ports array if available, otherwise fall back to a random port
43```
44*/
45export default function getPort(options?: Options): Promise<number>;
46
47/**
48Generate port numbers in the given range `from`...`to`.
49
50@param from - The first port of the range. Must be in the range `1024`...`65535`.
51@param to - The last port of the range. Must be in the range `1024`...`65535` and must be greater than `from`.
52@returns The port numbers in the range.
53
54@example
55```
56import getPort, {portNumbers} from 'get-port';
57
58console.log(await getPort({port: portNumbers(3000, 3100)}));
59// Will use any port from 3000 to 3100, otherwise fall back to a random port
60```
61*/
62export function portNumbers(from: number, to: number): Iterable<number>;