You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js使用spawn运行Windows本地exe文件报错求助

错误原因排查
  • 重复调用shell环境:同时设置shell: true又手动传入cmd /s /c,会导致命令解析混乱,cd后的目录上下文无法正确应用到exe的执行环境。
  • cd命令执行失败:如果expectedOutputPath路径不存在、包含未正确转义的特殊字符(比如空格),cd命令会直接失败,后续自然找不到目标exe文件。
  • 相对路径依赖失效:通过cd &&嵌套执行的方式,可能导致.\\${jobId}.exe的相对路径无法正确指向目标目录。
解决方案

1. 用spawn原生参数切换工作目录(推荐)

不需要手动写cd命令,spawn自带cwd参数可以直接指定进程的工作目录,避免shell解析问题,更可靠:

export const expectedOutput = (problemID, input) => {
  const jobId = `problemID${problemID}`;
  console.log("this is the expected output path ", expectedOutputPath);
  return new Promise((resolve, reject) => {
    let output = "";
    // 直接指定exe文件名,通过cwd参数切换到目标路径
    const process = spawn(`${jobId}.exe`, [], { 
      cwd: expectedOutputPath,
      shell: true // Windows环境下可保留,确保exe能被正确执行
    });
    process.stdin.write(input);
    process.stdin.end();
    process.stdout.on("data", (data) => {
      console.log("here at stdout");
      output += data.toString();
    });
    process.stderr.on("data", (data) => {
      console.log("here at stderr", data);
      output += data.toString();
    });
    process.on("close", (code) => {
      if (code === 0) {
        resolve(output);
      } else {
        console.log(output, typeof output);
        reject(
          `program ended with exit code ${code}, ${output.error || output}`
        );
      }
    });
  });
};

2. 修复原有cmd调用方式(若坚持使用cd命令)

如果一定要保留cd &&的写法,需去掉重复的shell配置,确保命令被正确解析:

// 移除shell: true,因为已经手动调用cmd进程
const process = spawn("cmd", ["/s", "/c", command]);

同时要确认expectedOutputPath的路径真实存在,且路径中的特殊字符已被正确包裹在引号中。

3. 前置验证步骤

  • 打印${expectedOutputPath}\\${jobId}.exe的完整路径,确认文件确实存在。
  • 手动在命令行执行cd "你的expectedOutputPath" && .\\problemID1.exe,验证exe文件本身能正常运行,排除编译或文件损坏问题。

内容的提问来源于stack exchange,提问作者amudala gopikrishna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 00:45:04