import {createServer, Server} from 'net';

/**
 * Checks if a port is in use
 */
async function isPortFree(port: number, hostname?: string): Promise<boolean> {
  return new Promise((resolve, reject) => {
    const server: Server = createServer()
      .once('error', error => {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        if ((error as any).code === 'EADDRINUSE') {
          resolve(true);
        } else {
          reject(error);
        }
      })
      .once('listening', () => server.once('close', () => resolve(false)).close())
      .listen(port, hostname);
  });
}

export default {isPortFree};
