相关疑难解决方法(0)


在 Windows 上生成带有 child_process 的 NodeJs 脚本,为什么我需要“shell: true”来解决 ENOENT 错误?

我正在使用这段代码:

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

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

info.on('close', () => {
  console.log('closed');
}
Run Code Online (Sandbox Code Playgroud)

但我有这个错误:

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
Run Code Online (Sandbox Code Playgroud)

如果我使用:

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

有用!

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

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

这是正确的?

shell cmd spawn child-process node.js

5
推荐指数
1
解决办法
4455
查看次数

标签 统计

child-process ×2

node.js ×2

spawn ×2

cmd ×1

debugging ×1

error-handling ×1

shell ×1