Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

exec vs execFile nodeJs

I want to run a command in command-prompt using nodejs.
Based on https://dzone.com/articles/understanding-execfile-spawn-exec-and-fork-in-node, i used

child_process.execFile('protractor', ['./src/convertedJs/tempProtractorconfig.js'], (err, stdout, stderr) => {}

The above code throws a ENOENT error.
But when i run

child_process.exec('protractor ./src/convertedJs/tempProtractorconfig.js', (err,stdout,stderr) => {}`

everything works fine.
Can somebody explain what is happening?

like image 547
radio_head Avatar asked Sep 27 '17 10:09

radio_head


1 Answers

There is a difference between using child_process.exec() and child_process.execFile() in that the latter won't spawn a shell whereas the former will.

Nodejs documentation states:

On Windows, however, .bat and .cmd files are not executable on their own without a terminal, and therefore cannot be launched using child_process.execFile(). When running on Windows, .bat and .cmd files can be invoked using child_process.spawn() with the shell option set, with child_process.exec(), or by spawning cmd.exe and passing the .bat or .cmd file as an argument (which is what the shell option and child_process.exec() do).

I could launch them... though not without problem.

My observations:

  • Running the following child_process.execFile('ls', ...) works on Linux whereas child_process.execFile('dir', ...) doesn't work on Windows.
  • specifying the fullpath to the protractor executable on Windows, e.g. child_process.execFile('C:\\Users\\Jperl\\AppData\\Roaming\\npm\\protractor.cmd', ...) works as expected! No shell means we don't have access to the path variable.

Don't use execFile for Windows at all. Instead use either spawn or exec:

var protractor = child_process.spawn('protractor', ['./src/convertedJs/tempProtractorconfig.js'], {shell: true});

or

var protractor = child_process.spawn('cmd', ['/c', 'protractor', './src/convertedJs/tempProtractorconfig.js']);
like image 188
jperl Avatar answered Nov 07 '22 22:11

jperl