child_process.execFile(file[, args][, options][, callback])


child_process.exec() 类似,除了默认不衍生 shell。 可执行的 file 会被直接衍生为一个新进程,这使得它比 child_process.exec() 更高效。

因为没有衍生 shell,所以不支持 I/O 重定向或文件查找等功能。

const { execFile } = require('child_process');
const child = execFile('node', ['--version'], (error, stdout, stderr) => {
  if (error) {
    throw error;
  }
  console.log(stdout);
});

传给 callbackstdoutstderr 包含子进程的输出。 默认情况下,Node.js 会将输出解码成 UTF-8 字符串。 encoding 用于指定解码 stdoutstderr 的字符编码。 如果 encoding'buffer' 或无效的字符编码,则传入 callback 的会是 Buffer

如果调用此方法的 util.promisify() 版本,则返回的 Promise 会返回具有 stdout 属性和 stderr 属性的对象。

const util = require('util');
const execFile = util.promisify(require('child_process').execFile);
async function getVersion() {
  const { stdout } = await execFile('node', ['--version']);
  console.log(stdout);
}
getVersion();

The child_process.execFile() function is similar to child_process.exec() except that it does not spawn a shell by default. Rather, the specified executable file is spawned directly as a new process making it slightly more efficient than child_process.exec().

The same options as child_process.exec() are supported. Since a shell is not spawned, behaviors such as I/O redirection and file globbing are not supported.

const { execFile } = require('child_process');
const child = execFile('node', ['--version'], (error, stdout, stderr) => {
  if (error) {
    throw error;
  }
  console.log(stdout);
});

The stdout and stderr arguments passed to the callback will contain the stdout and stderr output of the child process. By default, Node.js will decode the output as UTF-8 and pass strings to the callback. The encoding option can be used to specify the character encoding used to decode the stdout and stderr output. If encoding is 'buffer', or an unrecognized character encoding, Buffer objects will be passed to the callback instead.

If this method is invoked as its util.promisify()ed version, it returns a Promise for an Object with stdout and stderr properties. In case of an error (including any error resulting in an exit code other than 0), a rejected promise is returned, with the same error object given in the callback, but with an additional two properties stdout and stderr.

const util = require('util');
const execFile = util.promisify(require('child_process').execFile);
async function getVersion() {
  const { stdout } = await execFile('node', ['--version']);
  console.log(stdout);
}
getVersion();

If the shell option is enabled, do not pass unsanitized user input to this function. Any input containing shell metacharacters may be used to trigger arbitrary command execution.