Ask the OS for an ephemeral free port on `host`.
(host: string)
| 98 | |
| 99 | /** Ask the OS for an ephemeral free port on `host`. */ |
| 100 | function getFreePort(host: string): Promise<number> { |
| 101 | return new Promise((resolvePromise, reject) => { |
| 102 | const probe = createServer(); |
| 103 | probe.once('error', reject); |
| 104 | probe.listen({ host, port: 0 }, () => { |
| 105 | const address = probe.address(); |
| 106 | if (address === null || typeof address === 'string') { |
| 107 | probe.close(() => reject(new Error('failed to allocate a free port'))); |
| 108 | return; |
| 109 | } |
| 110 | const { port } = address; |
| 111 | probe.close(() => resolvePromise(port)); |
| 112 | }); |
| 113 | }); |
| 114 | } |
| 115 | |
| 116 | /** |
| 117 | * How many consecutive `preferred + n` ports to probe before giving up and |
no test coverage detected