()
| 8 | * @returns A promise that resolves with an available port number. |
| 9 | */ |
| 10 | export function findFreePort(): Promise<number> { |
| 11 | return new Promise<number>((resolve, reject) => { |
| 12 | const srv = createServer(); |
| 13 | srv.once('listening', () => { |
| 14 | const address = srv.address(); |
| 15 | if (!address || typeof address === 'string') { |
| 16 | // Should not happen with TCP, but good for type safety |
| 17 | srv.close(() => reject(new Error('Failed to get server address'))); |
| 18 | return; |
| 19 | } |
| 20 | const port = address.port; |
| 21 | srv.close((e) => (e ? reject(e) : resolve(port))); |
| 22 | }); |
| 23 | |
| 24 | // If an error happens (e.g. during bind), the server is not listening, |
| 25 | // so we should not call close(). |
| 26 | srv.once('error', (e) => reject(e)); |
| 27 | // Explicitly listen on IPv4 localhost to avoid firewall prompts, IPv6 binding issues, and ensure consistency. |
| 28 | srv.listen(0, '127.0.0.1'); |
| 29 | }); |
| 30 | } |
no test coverage detected