child_process.exec(command[, options][, callback])


衍生一个 shell 并在 shell 中执行 command,并缓冲产生的输出。 command 会被 shell 直接执行,所以 command 中的特殊字符(因shell而异)需要相应的处理:

exec('"/path/to/test file/test.sh" arg1 arg2');
// 使用双引号,则路径中的空格不会被当成多个参数。

exec('echo "The \\$HOME variable is $HOME"');
// 第一个 $HOME 会被转义,第二个则不会。

如果指定了 callback,则调用时会传入参数 (error, stdout, stderr)。 当成功时,error 会是 null。 当出错时,error 会是 Error 实例。 error.code 属性是子进程的退出码,error.signal 是终止进程的信号。 任何非 0 的退出码都会被视为出错。

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

const { exec } = require('child_process');
exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => {
  if (error) {
    console.error(`执行出错: ${error}`);
    return;
  }
  console.log(`stdout: ${stdout}`);
  console.log(`stderr: ${stderr}`);
});

如果 timeout 大于 0,则当子进程运行超过 timeout 毫秒时,父进程就会发送带 killSignal 属性(默认为 'SIGTERM')的信号。

不像 POSIX 中的 exec(3)child_process.exec() 不会替换现有的进程,且使用 shell 来执行命令。

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

const util = require('util');
const exec = util.promisify(require('child_process').exec);

async function lsExample() {
  const { stdout, stderr } = await exec('ls');
  console.log('stdout:', stdout);
  console.log('stderr:', stderr);
}
lsExample();

Spawns a shell then executes the command within that shell, buffering any generated output. The command string passed to the exec function is processed directly by the shell and special characters (vary based on shell) need to be dealt with accordingly:

exec('"/path/to/test file/test.sh" arg1 arg2');
// Double quotes are used so that the space in the path is not interpreted as
// multiple arguments

exec('echo "The \\$HOME variable is $HOME"');
// The $HOME variable is escaped in the first instance, but not in the second

Never pass unsanitized user input to this function. Any input containing shell metacharacters may be used to trigger arbitrary command execution.

If a callback function is provided, it is called with the arguments (error, stdout, stderr). On success, error will be null. On error, error will be an instance of Error. The error.code property will be the exit code of the child process while error.signal will be set to the signal that terminated the process. Any exit code other than 0 is considered to be an error.

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.

const { exec } = require('child_process');
exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => {
  if (error) {
    console.error(`exec error: ${error}`);
    return;
  }
  console.log(`stdout: ${stdout}`);
  console.log(`stderr: ${stderr}`);
});

If timeout is greater than 0, the parent will send the signal identified by the killSignal property (the default is 'SIGTERM') if the child runs longer than timeout milliseconds.

Unlike the exec(3) POSIX system call, child_process.exec() does not replace the existing process and uses a shell to execute the command.

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 exec = util.promisify(require('child_process').exec);

async function lsExample() {
  const { stdout, stderr } = await exec('ls');
  console.log('stdout:', stdout);
  console.log('stderr:', stderr);
}
lsExample();