4

I'm using this code:

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

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

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

But I have this error:

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

If I use instead:

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

it works!

But why I need shell: true? I need also to see the stdout of that spawn, so I'm also using this:

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

It's correct?

1 Answers1

4

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 project
let info = spawn('npm', ['-v'], { cwd: projectPath });

let result = '';
info.stdout.on('data', function(data) {  
  result += data.toString();
  console.log(result);
}
Kir Chou
  • 2,980
  • 1
  • 36
  • 48
  • Yes, of course, but I need the stdout "live" not at the end of my commands. How to with exec? –  Jul 08 '17 at 14:00
  • I got your reason of using spawn, have you tried cwd as a parameter? I have updated the code. Please give a try. – Kir Chou Jul 08 '17 at 14:20
  • 2
    Is not working on windows the cwd. I tried every path mode: absolute, relative, back and forward slash. Nothing. –  Jul 08 '17 at 17:39