Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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);

Expand Down
46 changes: 46 additions & 0 deletions src/utils/portCheck.ts
Original file line number Diff line number Diff line change
@@ -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<boolean> {
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<boolean> {
try {
const result = await isPortAvailable(port);
return !result;
} catch (error) {
// If there's an error checking, assume it's in use
return true;
}
}