child_process.exec(command[, options][, callback])
command<string> 要运行的命令,参数以空格分隔。options<Object>cwd<string> | <URL> 子进程的当前工作目录。 默认值:process.cwd()。env<Object> 环境变量键值对。 默认值:process.env。encoding<string> 默认值:'utf8'shell<string> 用于执行命令的 shell。 请参阅 shell 的要求和默认的 Windows shell。 默认值: Unix 上是'/bin/sh',Windows 上是process.env.ComSpec。signal<AbortSignal> 允许使用中止信号中止子进程。timeout<number> 默认值:0maxBuffer<number> 标准输出或标准错误上允许的最大数据量(以字节为单位)。 如果超过,则子进程将终止并截断任何输出。 请参阅 maxBuffer 和 Unicode 的注意事项。 默认值:1024 * 1024。killSignal<string> | <integer> 默认值:'SIGTERM'uid<number> 设置进程的用户标识(参见setuid(2))。gid<number> 设置进程的群组标识(参见setgid(2))。windowsHide<boolean> 隐藏通常在 Windows 系统上创建的子进程控制台窗口。 默认值:false。
callback<Function> 当进程终止时使用输出调用。- 返回: <ChildProcess>
衍生 shell,然后在该 shell 中执行 command,缓冲任何生成的输出。
传给执行函数的 command 字符串由 shell 直接处理,特殊字符(因 shell 而异)需要进行相应处理:
const { exec } = require('node:child_process');
exec('"/path/to/test file/test.sh" arg1 arg2');
// 使用双引号,这样路径中的空格就不会被解释为多个参数的分隔符。
exec('echo "The \\$HOME variable is $HOME"');
// $HOME 变量在第一个实例中被转义,但在第二个实例中没有。切勿将未经处理的用户输入传给此函数。 任何包含 shell 元字符的输入都可用于触发任意命令执行。
如果提供了 callback 函数,则使用参数 (error, stdout, stderr) 调用它。
成功后,error 将是 null。
出错时,error 将是 Error 的实例。
error.code 属性将是进程的退出码。
按照惯例,除 0 之外的任何退出码都表示错误。
error.signal 将是终止进程的信号。
传给回调的 stdout 和 stderr 参数将包含子进程的标准输出和标准错误的输出。
默认情况下,Node.js 会将输出解码为 UTF-8 并将字符串传给回调。
encoding 选项可用于指定用于解码标准输出和标准错误的输出的字符编码。
如果 encoding 是 'buffer' 或无法识别的字符编码,则 Buffer 对象将被传给回调。
const { exec } = require('node: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.error(`stderr: ${stderr}`);
});如果 timeout 大于 0,则如果子进程运行时间超过 timeout 毫秒,父进程将发送由 killSignal 属性(默认为 'SIGTERM')标识的信号。
与 exec(3) POSIX 系统调用不同,child_process.exec() 不替换现有进程,而是使用 shell 来执行命令。
如果此方法作为其 util.promisify() 版本被调用,则其将为具有 stdout 和 stderr 属性的 Object 返回 Promise。
返回的 ChildProcess 实例作为 child 属性附加到 Promise。
如果出现错误(包括任何导致退出码不是 0 的错误),则将返回被拒绝的 promise,其具有与回调中给定相同的 error 对象,但有两个额外的属性 stdout 和 stderr。
const util = require('node:util');
const exec = util.promisify(require('node:child_process').exec);
async function lsExample() {
const { stdout, stderr } = await exec('ls');
console.log('stdout:', stdout);
console.error('stderr:', stderr);
}
lsExample();如果启用了 signal 选项,则在相应的 AbortController 上调用 .abort() 与在子进程上调用 .kill() 类似,只是传给回调的错误将是 AbortError:
const { exec } = require('node:child_process');
const controller = new AbortController();
const { signal } = controller;
const child = exec('grep ssh', { signal }, (error) => {
console.log(error); // 一个 AbortError
});
controller.abort();command<string> The command to run, with space-separated arguments.options<Object>cwd<string> | <URL> Current working directory of the child process. Default:process.cwd().env<Object> Environment key-value pairs. Default:process.env.encoding<string> Default:'utf8'shell<string> Shell to execute the command with. See Shell requirements and Default Windows shell. Default:'/bin/sh'on Unix,process.env.ComSpecon Windows.signal<AbortSignal> allows aborting the child process using an AbortSignal.timeout<number> Default:0maxBuffer<number> Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated and any output is truncated. See caveat atmaxBufferand Unicode. Default:1024 * 1024.killSignal<string> | <integer> Default:'SIGTERM'uid<number> Sets the user identity of the process (seesetuid(2)).gid<number> Sets the group identity of the process (seesetgid(2)).windowsHide<boolean> Hide the subprocess console window that would normally be created on Windows systems. Default:false.
callback<Function> called with the output when process terminates.- Returns: <ChildProcess>
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:
const { exec } = require('node:child_process');
exec('"/path/to/test file/test.sh" arg1 arg2');
// Double quotes are used so that the space in the path is not interpreted as
// a delimiter of 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 process. By convention, any exit code other than 0
indicates an error. error.signal will be the signal that terminated the
process.
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('node: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.error(`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. The returned
ChildProcess instance is attached to the Promise as a child property. 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 two additional properties stdout and stderr.
const util = require('node:util');
const exec = util.promisify(require('node:child_process').exec);
async function lsExample() {
const { stdout, stderr } = await exec('ls');
console.log('stdout:', stdout);
console.error('stderr:', stderr);
}
lsExample();If the signal option is enabled, calling .abort() on the corresponding
AbortController is similar to calling .kill() on the child process except
the error passed to the callback will be an AbortError:
const { exec } = require('node:child_process');
const controller = new AbortController();
const { signal } = controller;
const child = exec('grep ssh', { signal }, (error) => {
console.log(error); // an AbortError
});
controller.abort();