NodeJs script with child_process spawn on Windows, why I need 'shell: true' for ENOENT error?
While calling spawn itself, there is no npm
command under spawn. Thus you got that error message. Instead of using spawn itself, while adding shell: true
, spawn will use shell of your system to run that command. Since your system has npm
, it works.
let info = spawn('npm', ["-v"], {shell: true, stdio: 'inherit'});
It's correct?
The code is fine if your parameters of spawn are controllable. But generally, I suggest use pure spawn without using shell. The risk will reduce without touching shell directly.
Since you need the stream return from spawn. I have checked other solution here. Without shell: true
, You can use the code:
const { spawn} = require('child_process');let projectPath = ''//the path of your projectlet info = spawn('npm', ['-v'], { cwd: projectPath });let result = '';info.stdout.on('data', function(data) { result += data.toString(); console.log(result);}