* @param {string=} opt_host The bound host to test the port against. * Defaults to INADDR_ANY. * @return {!Promise } A promise that will resolve to a free port. If a * port cannot be found, the promise will be rejected.
(opt_host)
| 51 | */ |
| 52 | |
| 53 | function findFreePort(opt_host) { |
| 54 | return new Promise((resolve, reject) => { |
| 55 | const server = net.createServer() |
| 56 | server.on('listening', function () { |
| 57 | resolve(server.address().port) |
| 58 | server.close() |
| 59 | }) |
| 60 | server.on('error', (e) => { |
| 61 | if (e.code === 'EADDRINUSE' || e.code === 'EACCES') { |
| 62 | resolve('Unable to find a free port') |
| 63 | } else { |
| 64 | reject(e) |
| 65 | } |
| 66 | }) |
| 67 | // By providing 0 we let the operative system find an arbitrary port |
| 68 | server.listen(0, opt_host) |
| 69 | }) |
| 70 | } |
| 71 | |
| 72 | // PUBLIC API |
| 73 | module.exports = { |