关于node.js:exec与execFile nodeJs

exec vs execFile nodeJs

我想使用nodejs在命令提示符下运行命令。
基于https://dzone.com/articles/understanding-execfile-spawn-exec-and-fork-in-node,我使用了

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

上面的代码抛出ENOENT错误。
但是当我跑步时

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

一切正常。
有人可以解释发生了什么吗?


使用child_process.exec()和child_process.execFile()的区别在于,后者不会产生外壳,而前者会产生外壳。

Nodejs文档指出:

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

我可以启动它们……尽管并非没有问题。

我的观察:

  • 在Linux上运行以下child_process.execFile('ls', ...)可以运行,而在Windows上则不能运行child_process.execFile('dir', ...)
  • 在Windows上指定量角器可执行文件的完整路径,例如 child_process.execFile('C:\\Users\\Jperl\\AppData\
    oaming\
    pm\\protractor.cmd', ...)
    可以正常工作! 没有shell意味着我们无权访问path变量。

根本不要在Windows上使用execFile。 而是使用spawnexec

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

要么

1
var protractor = child_process.spawn('cmd', ['/c', 'protractor', './src/convertedJs/tempProtractorconfig.js']);

在nodejs v9.5.0中,exec在文件lib / child_process.js中定义如下

1
2
3
exports.exec = function(command /*, options, callback*/) {
var opts = normalizeExecArgs.apply(null, arguments);
return exports.execFile(opts.file, opts.options, opts.callback);

};

这意味着,最终exec调用execFile来执行命令,因此对于您来说execFile失败但exec不是