从子进程 exec 更改为 spawn 不起作用

Change from child process exec to spawn dont work

我使用子进程 exec 我需要切换到子进程 spawn

这对我有用。

var child = child_process.exec("npm install express --save" options, function (error, stdout, stderr) {
    .....
 });

当我切换到 spawn 时它不起作用我收到错误

var child = child_process.spawn("npm install express --save" options);


Error: spawn npm ENOENT
    at exports._errnoException (util.js:746:11)
    at Process.ChildProcess._handle.onexit (child_process.js:1053:32)
    at child_process.js:1144:20

我什至尝试 var child = child_process.spawn("npm", ["install express --save"], options);

它对我不起作用,可能是什么问题?

我猜你在 Windows 环境中。

所以,你必须进入终端,然后使用你想要的命令。

我们在 Node.js 文档 child_process.exec() 方法中看到,根据操作系统,默认情况下在其选项中已经有此规范。

shell String Shell to execute the command with (Default: '/bin/sh' on UNIX, 'cmd.exe' on Windows, The shell should understand the -c switch on UNIX or /s /c on Windows. On Windows, command line parsing should be compatible with cmd.exe.)

所以当使用 spawn 时,情况正在发生变化。

var child = child_process.spawn("cmd",["/c","npm install express --save"], options);

上面的代码块,启动Windows命令解释器的新实例(cmd)并执行字符串指定的命令,然后终止(/c),最后是我们的特定命令npm install express --save 适用于 Windows 命令解释器。windows cmd commands references