5 shell cmd spawn child-process node.js
我正在使用这段代码:
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)
这是正确的?
当调用spawn本身时,spawn下没有npm命令。因此您收到了该错误消息。在添加时shell: true,spawn 将使用系统的shell来运行该命令,而不是使用 spawn 本身。既然你的系统有npm,它就可以工作了。
let info = spawn('npm', ["-v"], {shell: true, stdio: 'inherit'});这是正确的?
如果您的spawn参数是可控的,那么代码就很好。但一般来说,我建议使用纯spawn而不使用shell。不直接接触外壳,风险就会降低。
因为您需要流从生成返回。我在这里检查了其他解决方案。Without 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);
}
Run Code Online (Sandbox Code Playgroud)