【问题标题】:NodeJs script with child_process spawn on Windows, why I need 'shell: true' for ENOENT error?在 Windows 上生成带有 child_process 的 NodeJs 脚本,为什么我需要 'shell: true' 来处理 ENOENT 错误?
【发布时间】:2017-12-12 16:47:21
【问题描述】:

我正在使用此代码:

const {
  spawn
} = require('child_process');

let info = spawn('npm', ["-v"]);

info.on('close', () => {
  console.log('closed');
}

但我有这个错误:

events.js:182
      throw er; // Unhandled 'error' event
      ^

Error: spawn npm ENOENT
    at exports._errnoException (util.js:1022:11)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:189:19)
    at onErrorNT (internal/child_process.js:366:16)
    at _combinedTickCallback (internal/process/next_tick.js:102:11)
    at process._tickCallback (internal/process/next_tick.js:161:9)
    at Function.Module.runMain (module.js:607:11)
    at startup (bootstrap_node.js:158:16)
    at bootstrap_node.js:575:3

如果我改用:

let info = spawn('npm', ["-v"], {shell: true});

有效!

但是为什么我需要shell: true?我还需要查看该生成的标准输出,所以我也在使用这个:

let info = spawn('npm', ["-v"], {shell: true, stdio: 'inherit'});

对吗?

【问题讨论】:

    标签: node.js shell cmd child-process spawn


    【解决方案1】:

    在调用 spawn 本身时,在 spawn 下没有 npm 命令。因此,您收到了该错误消息。在添加shell: true 时,spawn 将使用您系统的 shell 来运行该命令,而不是使用 spawn 本身。因为你的系统有npm,所以它可以工作。

    let info = spawn('npm', ["-v"], {shell: true, stdio: 'inherit'}); 对吗?

    如果您的 spawn 参数是可控的,则代码很好。但一般来说,我建议使用纯产卵而不使用外壳。不直接接触外壳,风险会降低。


    因为您需要从 spawn 中返回流。我检查了其他解决方案hereWithout shell: true,可以使用代码:

    const {
      spawn
    } = require('child_process');
    
    let projectPath = ''//the path of your project
    let info = spawn('npm', ['-v'], { cwd: projectPath });
    
    let result = '';
    info.stdout.on('data', function(data) {  
      result += data.toString();
      console.log(result);
    }
    

    【讨论】:

    • 是的,当然,但我需要标准输出“live”而不是在我的命令末尾。如何使用 exec?
    • 我知道你使用 spawn 的原因,你试过 cwd 作为参数吗?我已经更新了代码。请试一试。
    • 不能在 Windows 上运行 cwd。我尝试了每种路径模式:绝对、相对、反斜杠和正斜杠。什么都没有。
    猜你喜欢
    • 2015-02-15
    • 2016-08-01
    • 2015-07-13
    • 1970-01-01
    • 2020-03-16
    • 2021-04-27
    • 1970-01-01
    • 1970-01-01
    • 2020-07-11
    相关资源
    最近更新 更多