|
@@ -0,0 +1,40 @@
|
|
|
|
+const net = require('net');
|
|
|
|
+
|
|
|
|
+async function isPortBusy(port: number, host?: string): Promise<any> {
|
|
|
|
+ return new Promise((resolve, reject) => {
|
|
|
|
+ const socket = new net.Socket();
|
|
|
|
+
|
|
|
|
+ socket.setTimeout(1000); // Set a timeout for the connection
|
|
|
|
+
|
|
|
|
+ // Handle connection success
|
|
|
|
+ socket.connect(port, host? host : '127.0.0.1', () => {
|
|
|
|
+ socket.end();
|
|
|
|
+ resolve(true); // Port is busy
|
|
|
|
+ });
|
|
|
|
+
|
|
|
|
+ // Handle errors (e.g., connection refused)
|
|
|
|
+ socket.on('error', (err: any) => {
|
|
|
|
+ if (err.code === 'ECONNREFUSED') {
|
|
|
|
+ resolve(false); // Port is available
|
|
|
|
+ } else {
|
|
|
|
+ reject(err); // Other errors
|
|
|
|
+ }
|
|
|
|
+ });
|
|
|
|
+
|
|
|
|
+ // Handle timeout
|
|
|
|
+ socket.on('timeout', () => {
|
|
|
|
+ socket.destroy();
|
|
|
|
+ resolve(false); // Port is not responding
|
|
|
|
+ });
|
|
|
|
+ });
|
|
|
|
+}
|
|
|
|
+
|
|
|
|
+// Usage example
|
|
|
|
+const port = 3000;
|
|
|
|
+isPortBusy(port)
|
|
|
|
+ .then((busy) => {
|
|
|
|
+ console.log(`Port ${port} is ${busy ? 'busy' : 'available'}.`);
|
|
|
|
+ })
|
|
|
|
+ .catch((err) => {
|
|
|
|
+ console.error(`Error checking port ${port}:`, err.message);
|
|
|
|
+ });
|