簡體   English   中英

exec vs execFile nodeJs

[英]exec vs execFile nodeJs

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

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

上面的代碼拋出一個 ENOENT 錯誤。
但是當我跑

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

一切正常。
有人可以解釋發生了什么嗎?

使用child_process.exec()和child_process.execFile()之間的區別在於,后者不會產生外殼,而前者會產生外殼。

Nodejs 文檔指出:

但是,在Windows上,.bat和.cmd文件在沒有終端的情況下無法單獨執行,因此無法使用child_process.execFile()啟動。 在Windows上運行時,可以使用設置了shell選項的child_process.spawn(),child_process.exec()或通過生成cmd.exe並將.bat或.cmd文件作為參數(這是shell選項和child_process.exec()的作用)。

這很奇怪,因為我可以使用execFile()毫無問題地啟動.bat或.cmd文件...

第二版學習節點摘錄:

我們可以使用child_process.execFile()運行cmd或bat文件,就像我們可以在類似Unix的環境中運行文件一樣。 給定以下bat文件(my.bat):

 @echo off REM Next command generates a list of program files dir 

使用以下應用程序運行文件:

 var execfile = require(' child_process').execFile, child; child = execfile(' my.bat', function( error, stdout, stderr) { if (error = = null) { console.log(' stdout: ' + stdout); } }); 

力量,雪萊。 學習節點(Kindle位置4950-4956)。 O'Reilly Media。 Kindle版。

話雖這么說,但我不會提供明確的答案,只是我的觀察。

  • 在Linux上運行以下child_process.execFile('ls', ...)可以運行,而child_process.execFile('dir', ...)在Windows上則不能運行。
  • 在Windows上指定量角器可執行文件的完整路徑,例如child_process.execFile('C:\\\\Users\\\\Jperl\\\\AppData\\\\Roaming\\\\npm\\\\protractor.cmd', ...)可以正常工作! 那很奇怪。 也許由於某種原因我們無法訪問path變量,所以我們必須指定完整路徑嗎? 它與沒有外殼有關嗎? 我不能說。

盡可能不要在Windows上完全使用execFile。 而是使用spawnexec

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

要么

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

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

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不是

我還遇到了一些問題,通過使用“node myfile.js”啟動節點進程,但是當我添加 node.exe 的位置時,比如“node.exe/node.exe myfile.js 的路徑”,它工作正常,就像我期望

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM