diff --git a/src/index.ts b/src/index.ts index efb38f4e..18568667 100644 --- a/src/index.ts +++ b/src/index.ts @@ -11,6 +11,7 @@ import { isServiceRunning, savePid, } from "./utils/processCheck"; +import { isPortAvailable } from "./utils/portCheck"; import { CONFIG_FILE } from "./constants"; import { createStream } from 'rotating-file-stream'; import { HOME_DIR } from "./constants"; @@ -73,6 +74,17 @@ async function run(options: RunOptions = {}) { const port = config.PORT || 3456; + // Check port availability before starting the service + try { + const isAvailable = await isPortAvailable(port); + if (!isAvailable) { + console.log(`Port ${port} is already in use. Please stop the process using this port or change the PORT in your config file.`); + process.exit(1); + } + console.log(`Port ${port} is not in use. start process ....`); + } catch (error) { + console.log("Could not check port availability, proceeding with start..."); + } // Save the PID of the background process savePid(process.pid); diff --git a/src/utils/portCheck.ts b/src/utils/portCheck.ts new file mode 100644 index 00000000..7844f702 --- /dev/null +++ b/src/utils/portCheck.ts @@ -0,0 +1,46 @@ +import net from 'net'; + +/** + * Check if a port is available for use + * @param port The port number to check + * @returns Promise that resolves to true if port is available, false otherwise + */ +export async function isPortAvailable(port: number): Promise { + return new Promise((resolve) => { + const server = net.createServer(); + + server.once('error', (err: any) => { + if (err.code === 'EADDRINUSE') { + resolve(false); + } else { + // Some other error occurred + resolve(false); + } + }); + + server.once('listening', () => { + // Port is available, close the server + server.close(() => { + resolve(true); + }); + }); + + server.listen(port, '127.0.0.1'); + }); +} + +/** + * Check if a port is in use by trying to connect to it + * @param port The port number to check + * @param host The host to check (defaults to 127.0.0.1) + * @returns Promise that resolves to true if port is in use, false otherwise + */ +export async function isPortInUse(port: number, host: string = '127.0.0.1'): Promise { + try { + const result = await isPortAvailable(port); + return !result; + } catch (error) { + // If there's an error checking, assume it's in use + return true; + } +} \ No newline at end of file