import net from 'net'; /** * Wait until something is accepting connections on a local port * @author Jay Luker * @param port the local port to watch * @param opts - object containing all arguments * @param opts.timeoutMs give up after this many milliseconds; required, as * how long a wait is reasonable depends entirely on what the caller is * waiting for * @param opts.intervalMs how often to retry the connection, which also caps * each individual attempt * @param opts.giveUp optional callback; return true to abort the wait early * @returns true if the port opened, false on timeout or abort. A port that * isn't accepting connections is an expected outcome, not an error, so * nothing is thrown for it * @throws if port isn't a valid port number */ const waitForPort = async ( port: number, opts: { timeoutMs: number, intervalMs?: number, giveUp?: () => boolean, }, ): Promise => { const { timeoutMs, intervalMs = 500, giveUp, } = opts; /** * Make a single connection attempt against the port * @author Jay Luker * @returns true if something accepted the connection, false if the * connection was refused, dropped, or took longer than intervalMs * @throws if port isn't a valid port number, which net.createConnection * rejects synchronously rather than reporting as a connection error */ const tryOnce = () => { return new Promise((resolve) => { const socket = net.createConnection({ port, host: '127.0.0.1' }); // Cap each attempt so a stalled connect (e.g. a listener with a full // backlog) can't blow past the overall timeoutMs deadline socket.setTimeout(intervalMs); socket.on('timeout', () => { socket.destroy(); resolve(false); }); socket.on('connect', () => { socket.destroy(); resolve(true); }); socket.on('error', () => { socket.destroy(); resolve(false); }); }); }; const deadline = Date.now() + timeoutMs; while (Date.now() < deadline) { if (giveUp && giveUp()) { return false; } if (await tryOnce()) { return true; } await new Promise((resolve) => { setTimeout(resolve, intervalMs); }); } return false; }; export default waitForPort;