Hyper-V 常保留 2960-3059,3000 会 EACCES;ensure-port-free 与 Vite 代理从 apps/api/.env 读取 PORT
41 lines
996 B
JavaScript
41 lines
996 B
JavaScript
import { execSync } from 'node:child_process';
|
|
import { resolveApiDevPort } from './dev-api-target.mjs';
|
|
|
|
const port = process.argv[2] ?? resolveApiDevPort();
|
|
|
|
function killWindows(portNum) {
|
|
let out = '';
|
|
try {
|
|
out = execSync(`netstat -ano | findstr :${portNum}`, { encoding: 'utf8' });
|
|
} catch {
|
|
return;
|
|
}
|
|
|
|
const pids = new Set();
|
|
for (const line of out.split('\n')) {
|
|
if (!line.includes('LISTENING')) continue;
|
|
const pid = line.trim().split(/\s+/).at(-1);
|
|
if (pid && pid !== '0') pids.add(pid);
|
|
}
|
|
|
|
for (const pid of pids) {
|
|
try {
|
|
console.log(`[ensure-port-free] freeing :${portNum} (PID ${pid})`);
|
|
execSync(`taskkill /F /PID ${pid}`, { stdio: 'ignore' });
|
|
} catch {
|
|
// already gone
|
|
}
|
|
}
|
|
}
|
|
|
|
function killUnix(portNum) {
|
|
try {
|
|
execSync(`lsof -ti tcp:${portNum} | xargs -r kill -9`, { stdio: 'ignore' });
|
|
} catch {
|
|
// port already free
|
|
}
|
|
}
|
|
|
|
if (process.platform === 'win32') killWindows(port);
|
|
else killUnix(port);
|