* Checks to see if the port is in use by creating a server on that port. You should use the function * `isPortInUseEx()` if you want to do a more exhaustive check or a general purpose use for any host * * @param port port to use. Must be > 0 and <= 65535 * @param host host ip ad
(port: number, host: string)
| 51 | * in which case the Node.js default rules apply. |
| 52 | */ |
| 53 | public static isPortInUse(port: number, host: string): Promise<boolean> { |
| 54 | ConsoleLog(`isPortInUse: testing port ${host}:${port}`); |
| 55 | return new Promise((resolve, reject) => { |
| 56 | const server = net.createServer((c) => { |
| 57 | }); |
| 58 | server.once('error', (e) => { |
| 59 | const code: string = (e as any).code; |
| 60 | if (code && (code === 'EADDRINUSE') || (code === 'EACCES')) { |
| 61 | // console.log(`port ${host}:${port} is used`, code); |
| 62 | if (code === 'EACCES') { |
| 63 | // Technically, EACCES means permission denied, so we consider it as used |
| 64 | ConsoleLog(`isPortInUse: port ${host}:${port} returned code EACCES?`); |
| 65 | } |
| 66 | ConsoleLog(`isPortInUse: port ${host}:${port} is busy`); |
| 67 | resolve(true); // Port in use |
| 68 | } else { |
| 69 | // This should never happen so, log it always |
| 70 | ConsoleLog(`isPortInUse: port ${host}:${port} unexpected error `, e); |
| 71 | reject(e); // some other failure |
| 72 | } |
| 73 | server.close(); |
| 74 | }); |
| 75 | |
| 76 | server.once('close', () => { |
| 77 | ConsoleLog(`isPortInUse: port ${host}:${port} is free`); |
| 78 | resolve(false); |
| 79 | }); |
| 80 | |
| 81 | server.listen(port, host, () => { |
| 82 | server.close(); |
| 83 | }); |
| 84 | }); |
| 85 | } |
| 86 | |
| 87 | /** |
| 88 | * Checks to see if the port is in use by creating a server on that port if a localhost or alias |
no test coverage detected