Search code examples
node.jschild-process

Change from child process exec to spawn dont work


I use the child process exec and I need to switch to child process spawn

This is working for me.

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

when I do the switch to spawn it doesnt work I got error

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

I try even with var child = child_process.spawn("npm", ["install express --save"], options);

and it doesnt work for me, what can be the issue?


Solution

  • I guess you are on Windows environment.

    So, you have to enter terminal and then use commands what you want.

    We see in Node.js docs child_process.exec() method already has this spec in its options by default according to operating system.

    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.)

    So when using spawn, things are changing.

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

    The above code block, starts new instance of Windows command interpreter(cmd) and carries out command specified by string and then terminates(/c) , finally our specific command npm install express --save works on Windows command interpreter.windows cmd commands references