|
| 1 | +#!/usr/bin/env node |
| 2 | + |
| 3 | +// 释放被占用的端口:找到监听该端口的进程,连同启动它的工具链父进程一起结束。 |
| 4 | +// 用法: node kill-port.js <端口> |
| 5 | +// |
| 6 | +// 为什么不直接杀监听进程:`tsx --watch` 这类父进程会在子进程被杀后重新拉起, |
| 7 | +// 因此必须沿祖先链把整个工具链一起结束(遇到 shell 终端即停止,不会关闭终端)。 |
| 8 | + |
| 9 | +const { execFileSync } = require("node:child_process"); |
| 10 | + |
| 11 | +const port = Number(process.argv[2]); |
| 12 | +if (!Number.isInteger(port) || port <= 0) { |
| 13 | + console.error("用法: node kill-port.js <端口>"); |
| 14 | + process.exit(1); |
| 15 | +} |
| 16 | + |
| 17 | +function findListenerPids() { |
| 18 | + if (process.platform === "win32") { |
| 19 | + const output = execFileSync("netstat", ["-ano"], { encoding: "utf8" }); |
| 20 | + const pids = new Set(); |
| 21 | + for (const line of output.split("\n")) { |
| 22 | + const columns = line.trim().split(/\s+/); |
| 23 | + // 协议 本地地址 远程地址 状态 PID |
| 24 | + if (columns.length === 5 && columns[3] === "LISTENING" && columns[1].endsWith(`:${port}`)) { |
| 25 | + pids.add(Number(columns[4])); |
| 26 | + } |
| 27 | + } |
| 28 | + return [...pids]; |
| 29 | + } |
| 30 | + // lsof 在没有找到监听进程时以退出码 1 结束,属正常情况,按空结果处理 |
| 31 | + let output = ""; |
| 32 | + try { |
| 33 | + output = execFileSync("lsof", [`-ti:${port}`, "-sTCP:LISTEN"], { encoding: "utf8" }); |
| 34 | + } catch (error) { |
| 35 | + output = error.stdout || ""; |
| 36 | + } |
| 37 | + return [...new Set(output.split("\n").map(Number).filter(Boolean))]; |
| 38 | +} |
| 39 | + |
| 40 | +const TOOLCHAIN_NAMES = new Set(["node", "node.exe", "pnpm", "npm", "npx", "cross-env", "tsx", "shx"]); |
| 41 | +const TOOLCHAIN_CMD = /pnpm|tsx|cross-env/; |
| 42 | + |
| 43 | +function isToolchainProcess(name, commandLine) { |
| 44 | + if (TOOLCHAIN_NAMES.has(name)) return true; |
| 45 | + // Windows 上 pnpm 会包一层 cmd.exe /c pnpm ... |
| 46 | + return name === "cmd.exe" && TOOLCHAIN_CMD.test(commandLine); |
| 47 | +} |
| 48 | + |
| 49 | +function findWinProcess(procId) { |
| 50 | + const script = `Get-CimInstance Win32_Process -Filter "ProcessId=${procId}" | Select-Object -First 1 | ForEach-Object { "$($_.ParentProcessId)|$($_.Name)|$($_.CommandLine)" }`; |
| 51 | + try { |
| 52 | + const output = execFileSync("powershell", ["-NoProfile", "-Command", script], { encoding: "utf8" }).trim(); |
| 53 | + if (!output) return null; |
| 54 | + const separator = output.indexOf("|"); |
| 55 | + const parent = Number(output.slice(0, separator)); |
| 56 | + const rest = output.slice(separator + 1); |
| 57 | + const nameSeparator = rest.indexOf("|"); |
| 58 | + return { parent, name: rest.slice(0, nameSeparator), commandLine: rest.slice(nameSeparator + 1) }; |
| 59 | + } catch { |
| 60 | + return null; |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +function collectAncestorTree(pid) { |
| 65 | + const pids = [pid]; |
| 66 | + let current = pid; |
| 67 | + for (let depth = 0; depth < 15; depth += 1) { |
| 68 | + if (process.platform === "win32") { |
| 69 | + const info = findWinProcess(current); |
| 70 | + if (!info || !info.parent || info.parent <= 4) break; |
| 71 | + const parent = findWinProcess(info.parent); |
| 72 | + if (!parent || !isToolchainProcess(parent.name, parent.commandLine)) break; |
| 73 | + pids.push(info.parent); |
| 74 | + current = info.parent; |
| 75 | + } else { |
| 76 | + let parentPid; |
| 77 | + let parentName; |
| 78 | + try { |
| 79 | + parentPid = Number(execFileSync("ps", ["-o", "ppid=", "-p", String(current)], { encoding: "utf8" }).trim()); |
| 80 | + parentName = execFileSync("ps", ["-o", "comm=", "-p", String(parentPid)], { encoding: "utf8" }).trim(); |
| 81 | + } catch { |
| 82 | + break; |
| 83 | + } |
| 84 | + if (!parentPid || parentPid <= 1) break; |
| 85 | + if (!isToolchainProcess(parentName.split("/").pop(), "")) break; |
| 86 | + pids.push(parentPid); |
| 87 | + current = parentPid; |
| 88 | + } |
| 89 | + } |
| 90 | + return pids; |
| 91 | +} |
| 92 | + |
| 93 | +function killProcess(target) { |
| 94 | + try { |
| 95 | + if (process.platform === "win32") { |
| 96 | + execFileSync("taskkill", ["/PID", String(target), "/F"], { stdio: "ignore" }); |
| 97 | + } else { |
| 98 | + process.kill(target, "SIGKILL"); |
| 99 | + } |
| 100 | + } catch { |
| 101 | + // 进程可能已经退出,忽略 |
| 102 | + } |
| 103 | +} |
| 104 | + |
| 105 | +const pids = findListenerPids(); |
| 106 | +if (pids.length === 0) { |
| 107 | + console.log(`端口 ${port} 已空闲`); |
| 108 | + process.exit(0); |
| 109 | +} |
| 110 | +for (const pid of pids) { |
| 111 | + const tree = collectAncestorTree(pid); |
| 112 | + for (const target of tree) { |
| 113 | + killProcess(target); |
| 114 | + } |
| 115 | + console.log(`已结束进程: ${tree.join(" <- ")}`); |
| 116 | +} |
| 117 | +console.log(`已释放端口 ${port}`); |
0 commit comments