File size: 1,606 Bytes
1f0573c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// Script to kill any existing processes on port 7860
import { execSync } from 'child_process';

const PORT = 7860;

try {
  console.log(`Checking for processes using port ${PORT}...`);

  // Different commands based on OS
  let command;
  if (process.platform === 'win32') {
    command = `netstat -ano | findstr :${PORT}`;
  } else {
    command = `lsof -i :${PORT} | grep LISTEN | awk '{print $2}'`;
  }

  const result = execSync(command, { encoding: 'utf8' });

  if (result) {
    console.log(`Found processes using port ${PORT}. Attempting to kill...`);

    if (process.platform === 'win32') {
      // Extract PID from Windows netstat output
      const pidMatches = result.match(/\s+(\d+)$/m);
      if (pidMatches && pidMatches[1]) {
        const pid = pidMatches[1];
        execSync(`taskkill /F /PID ${pid}`);
        console.log(`Killed process with PID ${pid}`);
      }
    } else {
      // On Unix systems, kill processes directly from lsof output
      const pids = result.trim().split('\n');
      for (const pid of pids) {
        if (pid) {
          execSync(`kill -9 ${pid}`);
          console.log(`Killed process with PID ${pid}`);
        }
      }
    }

    console.log(`Port ${PORT} is now available`);
  } else {
    console.log(`No processes found using port ${PORT}`);
  }
} catch (error) {
  // If no processes are found, lsof/netstat might return non-zero exit code
  if (error.status !== 0 && !error.stdout && !error.stderr) {
    console.log(`No processes found using port ${PORT}`);
  } else {
    console.error(`Error checking port ${PORT}:`, error.message);
  }
}