* Tests if a port is free. * @param {number} port The port to test. * @param {string=} opt_host The bound host to test the port against. * Defaults to INADDR_ANY. * @return {!Promise } A promise that will resolve with whether the port * is free.
(port, opt_host)
| 28 | * is free. |
| 29 | */ |
| 30 | function isFree(port, opt_host) { |
| 31 | return new Promise((resolve, reject) => { |
| 32 | const server = net.createServer().on('error', function (e) { |
| 33 | if (e.code === 'EADDRINUSE' || e.code === 'EACCES') { |
| 34 | resolve(false) |
| 35 | } else { |
| 36 | reject(e) |
| 37 | } |
| 38 | }) |
| 39 | |
| 40 | server.listen(port, opt_host, function () { |
| 41 | server.close(() => resolve(true)) |
| 42 | }) |
| 43 | }) |
| 44 | } |
| 45 | |
| 46 | /** |
| 47 | * @param {string=} opt_host The bound host to test the {@code port} against. |