{"record":{"id":"83f672921667c1dd","repo":"docmirror/dev-sidecar","slug":"error-83f672","errorCode":null,"errorMessage":"没有找到占用该端口的进程","messagePattern":"没有找到占用该端口的进程","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"info","filePath":"packages/core/src/shell/scripts/kill-by-port.js","lineNumber":29,"sourceCode":" * - mac:     lsof → fuser\n */\nconst executor = {\n  async windows (exec, { port }) {\n    // 主方案：PowerShell（更可靠，跨平台一致，Win7+ 默认可用）\n    try {\n      const cmds = [\n        // 查找处于 Listen 状态的 TCP 连接并终止对应进程\n        `$conn = Get-NetTCPConnection -LocalPort ${port} -ErrorAction SilentlyContinue | Where-Object { $_.State -eq 'Listen' } | Select-Object -First 1; if ($conn) { Stop-Process -Id $conn.OwningProcess -Force }`,\n      ]\n      await exec(cmds, { type: 'ps' })\n      return true\n    } catch (psError) {\n      // 备选方案：CMD netstat + taskkill（Win7 无 pwsh 或 pwsh 执行失败时回退）\n      // 分两步执行，避免 for /f 在 cmd /s /c 下的引号解析问题\n      try {\n        const output = await exec([`netstat -aon | find \":${port}\"`], { type: 'cmd', printErrorLog: false })\n        if (!output) {\n          throw new Error('没有找到占用该端口的进程')\n        }\n\n        // 解析 netstat 输出，提取处于 LISTENING 状态的 PID\n        const lines = output.split(/\\r?\\n/)\n        let killed = false\n        for (const line of lines) {\n          if (!line.includes('LISTENING')) {\n            continue\n          }\n          const parts = line.trim().split(/\\s+/)\n          const pid = parts[parts.length - 1]\n          if (pid && /^\\d+$/.test(pid)) {\n            await exec([`taskkill /f /pid ${pid} /t`], { type: 'cmd', printErrorLog: false })\n            killed = true\n          }\n        }\n        if (!killed) {\n          throw new Error('未找到处于 LISTENING 状态的进程')","sourceCodeStart":11,"sourceCodeEnd":47,"githubUrl":"https://github.com/docmirror/dev-sidecar/blob/7710cd56cce760c708f30b01d2d4056eb8c402d5/packages/core/src/shell/scripts/kill-by-port.js#L11-L47","documentation":"When killing the process listening on a port on Windows, the primary PowerShell path may fail (e.g. Win7 without pwsh), and the fallback runs `netstat -aon | find \":port\"` via cmd. If netstat returns nothing, there is no process bound to that port, so the fallback throws `没有找到占用该端口的进程` (no process found occupying this port).","triggerScenarios":"Calling the kill-by-port shell API with a `port` that currently has no listener on Windows, or where netstat output is empty/filtered out (port already freed between check and kill; IPv6-only binding not matched by `find \":port\"` with unusual formatting).","commonSituations":"Stopping dev-sidecar when the proxy already exited; restart scripts racing with process shutdown; typo'd port number; another tool already killed the listener.","solutions":["Check whether the port is actually in use first (`netstat -aon | find \":<port>\"`) and skip the kill when nothing is listening.","Verify the port number is the one dev-sidecar actually uses (default 31180/31181).","Treat the error as a no-op success in restart scripts — the goal (port free) is already achieved.","If the process exists but netstat misses it, run `Get-NetTCPConnection -LocalPort <port>` in PowerShell to get the PID and taskkill it manually."],"exampleFix":"// before\nawait DevSidecar.shell.killByPort({ port: 31181 })\n// after\nconst { execSync } = require('child_process')\nlet inUse = false\ntry {\n  inUse = execSync(`netstat -aon | find \":31181\"`).toString().length > 0\n} catch (e) { /* find returns non-zero when no match */ }\nif (inUse) {\n  await DevSidecar.shell.killByPort({ port: 31181 })\n}","handlingStrategy":"try-catch","validationCode":"const { execSync } = require('child_process')\nlet inUse = false\ntry {\n  execSync(`netstat -aon | find \":${port}\"`)\n  inUse = true\n} catch (e) { /* no match => nothing listening */ }\nif (!inUse) return // port already free, nothing to kill","typeGuard":"function isPortInUse (port) {\n  try {\n    require('child_process').execSync(`netstat -aon | find \":${port}\"`)\n    return true\n  } catch (e) { return false }\n}","tryCatchPattern":"try {\n  await DevSidecar.shell.killByPort({ port })\n} catch (err) {\n  if (err.message === '没有找到占用该端口的进程') {\n    log.info('port already free; nothing to kill')\n  } else { throw err }\n}","preventionTips":["Check netstat for a listener before killing","Treat this error as success in stop/restart flows","Confirm you are targeting the correct port (31180/31181 defaults)","Avoid racing kill calls immediately after process shutdown"],"tags":["windows","port","process-management"],"backgroundTag":"no-process-on-port","analyzedSha":"7710cd56cce760c708f30b01d2d4056eb8c402d5","analyzedAt":"2026-08-31T22:07:07.234Z","schemaVersion":2},"datasetVersion":"2026-08-31T22:30:34.772Z"}