child-process

Child process

子进程

Source Code: lib/child_process.js 源代码:lib/child_process.js

The node:child_process module provides the ability to spawn subprocesses in a manner that is similar, but not identical, to popen(3). This capability is primarily provided by the child_process.spawn() function:

node:child_process 模块提供以类似于 popen(3) 的方式生成子进程的功能,但并不完全相同。此功能主要由 child_process.spawn() 函数提供:

const { spawn } = require('node:child_process');
const ls = spawn('ls', ['-lh', '/usr']);

ls.stdout.on('data', (data) => {
  console.log(`stdout: ${data}`);
});

ls.stderr.on('data', (data) => {
  console.error(`stderr: ${data}`);
});

ls.on('close', (code) => {
  console.log(`child process exited with code ${code}`);
});

By default, pipes for stdin, stdout, and stderr are established between the parent Node.js process and the spawned subprocess. These pipes have limited (and platform-specific) capacity. If the subprocess writes to stdout in excess of that limit without the output being captured, the subprocess blocks waiting for the pipe buffer to accept more data. This is identical to the behavior of pipes in the shell. Use the { stdio: ‘ignore’ } option if the output will not be consumed.

默认情况下, stdin 、 stdout 和 stderr 的管道在父 Node.js 进程和生成的子进程之间建立。这些管道具有有限的(且特定于平台的)容量。如果子进程向 stdout 写入超出该限制的数据而未捕获输出,则子进程会阻塞,等待管道缓冲区接受更多数据。这与 shell 中管道的行为相同。如果不会使用输出,请使用 { stdio: ‘ignore’ } 选项。

The command lookup is performed using the options.env.PATH environment variable if env is in the options object. Otherwise, process.env.PATH is used. If options.env is set without PATH, lookup on Unix is performed on a default search path search of /usr/bin:/bin (see your operating system’s manual for execvpe/execvp), on Windows the current processes environment variable PATH is used.

如果 env 在 options 对象中,则使用 options.env.PATH 环境变量执行命令查找。否则,使用 process.env.PATH 。如果设置了 options.env 但没有 PATH ,则在 Unix 上执行查找,默认搜索路径为 /usr/bin:/bin (请参阅操作系统的 execvpe/execvp 手册),在 Windows 上使用当前进程的环境变量 PATH 。

On Windows, environment variables are case-insensitive. Node.js lexicographically sorts the env keys and uses the first one that case-insensitively matches. Only first (in lexicographic order) entry will be passed to the subprocess. This might lead to issues on Windows when passing objects to the env option that have multiple variants of the same key, such as PATH and Path.

在 Windows 上,环境变量不区分大小写。Node.js 按字典顺序对 env 键进行排序,并使用第一个不区分大小写匹配的键。只有第一个(按字典顺序)条目将传递给子进程。当将具有相同键的多个变体的对象(例如 PATH 和 Path )传递给 env 选项时,这可能会导致 Windows 上出现问题。

The child_process.spawn() method spawns the child process asynchronously, without blocking the Node.js event loop. The child_process.spawnSync() function provides equivalent functionality in a synchronous manner that blocks the event loop until the spawned process either exits or is terminated.

child_process.spawn() 方法异步生成子进程,而不会阻塞 Node.js 事件循环。 child_process.spawnSync() 函数以同步方式提供等效的功能,该方式会阻塞事件循环,直到生成的进程退出或终止。

For convenience, the node:child_process module provides a handful of synchronous and asynchronous alternatives to child_process.spawn() and child_process.spawnSync(). Each of these alternatives are implemented on top of child_process.spawn() or child_process.spawnSync().

为了方便起见, node:child_process 模块提供了一些 child_process.spawn() 和 child_process.spawnSync() 的同步和异步替代方案。这些替代方案中的每一个都在 child_process.spawn() 或 child_process.spawnSync() 的基础上实现。

child_process.exec(): spawns a shell and runs a command within that shell, passing the stdout and stderr to a callback function when complete. child_process.exec() :生成一个 shell 并运行该 shell 中的一个命令,在完成后将 stdout 和 stderr 传递给回调函数。

child_process.execFile(): similar to child_process.exec() except that it spawns the command directly without first spawning a shell by default. child_process.execFile() :类似于 child_process.exec() ,但它默认直接生成命令,而不会首先生成 shell。

child_process.fork(): spawns a new Node.js process and invokes a specified module with an IPC communication channel established that allows sending messages between parent and child. child_process.fork() :生成一个新的 Node.js 进程并调用一个指定的模块,并建立一个 IPC 通信通道,允许在父进程和子进程之间发送消息。

child_process.execSync(): a synchronous version of child_process.exec() that will block the Node.js event loop. child_process.execSync() : child_process.exec() 的同步版本,它将阻塞 Node.js 事件循环。

child_process.execFileSync(): a synchronous version of child_process.execFile() that will block the Node.js event loop. child_process.execFileSync() : child_process.execFile() 的同步版本,它将阻塞 Node.js 事件循环。

For certain use cases, such as automating shell scripts, the synchronous counterparts may be more convenient. In many cases, however, the synchronous methods can have significant impact on performance due to stalling the event loop while spawned processes complete. 对于某些用例(例如自动执行 shell 脚本),同步对应项可能更方便。然而,在许多情况下,由于在生成进程完成时会暂停事件循环,因此同步方法可能会对性能产生重大影响。

Asynchronous process creation

异步进程创建

The child_process.spawn(), child_process.fork(), child_process.exec(), and child_process.execFile() methods all follow the idiomatic asynchronous programming pattern typical of other Node.js APIs. 方法 child_process.spawn() 、 child_process.fork() 、 child_process.exec() 和 child_process.execFile() 都遵循其他 Node.js API 典型的惯用异步编程模式。

Each of the methods returns a ChildProcess instance. These objects implement the Node.js EventEmitter API, allowing the parent process to register listener functions that are called when certain events occur during the life cycle of the child process. 每个方法都会返回一个 ChildProcess 实例。这些对象会实现 Node.js EventEmitter API,允许父进程注册侦听器函数,这些函数会在子进程生命周期中发生某些事件时被调用。

The child_process.exec() and child_process.execFile() methods additionally allow for an optional callback function to be specified that is invoked when the child process terminates. 方法 child_process.exec() 和 child_process.execFile() 还允许指定一个可选的 callback 函数,该函数会在子进程终止时调用。

Spawning .bat and .cmd files on Windows 在 Windows 上生成 .bat 和 .cmd 文件#

The importance of the distinction between child_process.exec() and child_process.execFile() can vary based on platform. On Unix-type operating systems (Unix, Linux, macOS) child_process.execFile() can be more efficient because it does not spawn a shell by default. 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). In any case, if the script filename contains spaces it needs to be quoted. 在不同平台上, child_process.exec() 和 child_process.execFile() 之间区别的重要性可能有所不同。在 Unix 型操作系统(Unix、Linux、macOS)上, child_process.execFile() 可能会更高效,因为它默认不会生成 shell。然而,在 Windows 上, .bat 和 .cmd 文件本身在没有终端的情况下不可执行,因此无法使用 child_process.execFile() 启动。在 Windows 上运行时,可以使用 child_process.spawn() (设置了 shell 选项)、 child_process.exec() 或生成 cmd.exe 并传递 .bat 或 .cmd 文件作为参数(这是 shell 选项和 child_process.exec() 所做的)来调用 .bat 和 .cmd 文件。无论如何,如果脚本文件名包含空格,则需要加上引号。

// On Windows Only...
const { spawn } = require('node:child_process');
const bat = spawn('cmd.exe', ['/c', 'my.bat']);

bat.stdout.on('data', (data) => {
  console.log(data.toString());
});

bat.stderr.on('data', (data) => {
  console.error(data.toString());
});

bat.on('exit', (code) => {
  console.log(`Child exited with code ${code}`);
}); ```


// OR...

```js
const { exec, spawn } = require('node:child_process');
exec('my.bat', (err, stdout, stderr) => {
  if (err) {
    console.error(err);
    return;
  }
  console.log(stdout);
});

// Script with spaces in the filename:
const bat = spawn('"my script.cmd"', ['a', 'b'], { shell: true });
// or:
exec('"my script.cmd" a b', (err, stdout, stderr) => {
  // ...
}); 

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

  • command The command to run, with space-separated arguments.
  • command 要运行的命令,带有空格分隔的参数。
  • options
    • cwd | Current working directory of the child process. Default: process.cwd().
    • cwd | 子进程的当前工作目录。默认值: process.cwd() .
    • env Environment key-value pairs. Default: process.env.
    • env 环境键值对。默认值: process.env 。
    • encoding Default: ‘utf8’
    • encoding 默认值: ‘utf8’
    • shell Shell to execute the command with. See Shell requirements and Default Windows shell. Default: ‘/bin/sh’ on Unix, process.env.ComSpec on Windows.
    • shell 用于执行命令的 Shell。请参阅 Shell 要求和默认 Windows shell。默认值: ‘/bin/sh’ 在 Unix 上, process.env.ComSpec 在 Windows 上。
    • signal allows aborting the child process using an AbortSignal.
    • signal 允许使用 AbortSignal 中止子进程。
    • timeout Default: 0
    • timeout 默认值: 0
    • maxBuffer 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 at maxBuffer and Unicode. Default: 1024 * 1024.
    • maxBuffer stdout 或 stderr 上允许的最大数据量(以字节为单位)。如果超过,则终止子进程并截断任何输出。请参阅 maxBuffer 和 Unicode 中的注意事项。默认值: 1024 * 1024 .
    • killSignal | Default: ‘SIGTERM’
    • killSignal | 默认值: ‘SIGTERM’
    • uid Sets the user identity of the process (see setuid(2)).
    • uid 设置进程的用户标识(请参阅 setuid(2) )。
    • gid Sets the group identity of the process (see setgid(2)).
    • gid 设置进程的组标识(请参阅 setgid(2) )。
    • windowsHide Hide the subprocess console window that would normally be created on Windows systems. Default: false.
    • windowsHide 隐藏通常在 Windows 系统上创建的子进程控制台窗口。默认值: false .
    • callback called with the output when process terminates.
    • callback 在进程终止时使用输出调用。
    • error
    • stdout |
    • stderr |
    • Returns:
    • 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: 生成一个 shell,然后在该 shell 中执行 command ,缓冲任何生成的输出。

      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. COPY Never pass unsanitized user input to this function. Any input containing shell metacharacters may be used to trigger arbitrary command execution. 传递给 exec 函数的 字符串由 shell 直接处理,并且需要相应地处理特殊字符(根据 shell 而异): 切勿将未经清理的用户输入传递给此函数。任何包含 shell

      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. 传递给回调的 stdout 和 stderr 参数将包含子进程的 stdout 和 stderr 输出。默认情况下,Node.js 将解码输出为 UTF-8 并将字符串传递给回调。可以使用 encoding 选项来指定用于解码 stdout 和 stderr 输出的字符编码。如果 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}); }); COPY 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. 如果 timeout 大于 0 ,则如果子进程运行时间超过 timeout 毫秒,父进程将发送由 killSignal 属性标识的信号(默认值为 ‘SIGTERM’ )。

      Unlike the exec(3) POSIX system call, child_process.exec() does not replace the existing process and uses a shell to execute the command. 与 exec(3) POSIX 系统调用不同, child_process.exec() 不会替换现有进程,而是使用 shell 来执行命令。

      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. 如果将此方法作为其 util.promisify() ed 版本调用,它将为具有 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(); COPY 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: 如果启用了 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.error(error); // an AbortError }); controller.abort(); COPY child_process.execFile(file[, args][, options][, callback])# History 历史记录 file The name or path of the executable file to run. file 要运行的可执行文件的名称或路径。 args <string[]> List of string arguments. args 字符串参数列表。 options cwd | Current working directory of the child process. cwd | 子进程的当前工作目录。 env Environment key-value pairs. Default: process.env. env 环境键值对。默认值: process.env 。 encoding Default: ‘utf8’ encoding 默认值: ‘utf8’ timeout Default: 0 timeout 默认值: 0 maxBuffer 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 at maxBuffer and Unicode. Default: 1024 * 1024. maxBuffer 允许在 stdout 或 stderr 上的最大数据量(以字节为单位)。如果超出,则终止子进程并截断任何输出。请参阅 maxBuffer 和 Unicode 中的注意事项。默认值: 1024 * 1024 。 killSignal | Default: ‘SIGTERM’ killSignal | 默认值: ‘SIGTERM’ uid Sets the user identity of the process (see setuid(2)). uid 设置进程的用户标识(请参阅 setuid(2) )。 gid Sets the group identity of the process (see setgid(2)). gid 设置进程的组标识(请参阅 setgid(2) )。 windowsHide Hide the subprocess console window that would normally be created on Windows systems. Default: false. windowsHide 隐藏通常在 Windows 系统上创建的子进程控制台窗口。默认值: false 。 windowsVerbatimArguments No quoting or escaping of arguments is done on Windows. Ignored on Unix. Default: false. windowsVerbatimArguments 在 Windows 上不引用或转义参数。在 Unix 上忽略。默认值: false 。 shell | If true, runs command inside of a shell. Uses ‘/bin/sh’ on Unix, and process.env.ComSpec on Windows. A different shell can be specified as a string. See Shell requirements and Default Windows shell. Default: false (no shell). shell | 如果为 true ,则在 shell 内运行 command 。在 Unix 上使用 ‘/bin/sh’ ,在 Windows 上使用 process.env.ComSpec 。可以将不同的 shell 指定为字符串。请参阅 Shell 要求和默认 Windows shell。默认值: false (无 shell)。 signal allows aborting the child process using an AbortSignal. signal 允许使用 AbortSignal 中止子进程。 callback Called with the output when process terminates. callback 在进程终止时使用输出调用。 error stdout | stderr | Returns: 返回: 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(). 该 child_process.execFile() 函数类似于 child_process.exec() ,但默认情况下不会生成 shell。相反,指定的可执行文件 file 会直接作为新进程生成,使其比 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. 支持与 child_process.exec() 相同的选项。由于不会生成 shell,因此不支持 I/O 重定向和文件通配符等行为。

      const { execFile } = require(’node:child_process’); const child = execFile(’node’, [’–version’], (error, stdout, stderr) => { if (error) { throw error; } console.log(stdout); }); COPY 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. 传递给回调的 stdout 和 stderr 参数将包含子进程的 stdout 和 stderr 输出。默认情况下,Node.js 会将输出解码为 UTF-8 并将字符串传递给回调。 encoding 选项可用于指定用于解码 stdout 和 stderr 输出的字符编码。如果 encoding 为 ‘buffer’ 或无法识别的字符编码,则会将 Buffer 对象传递给回调。

      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. 如果此方法作为其 util.promisify() ed版本调用,它将返回一个 Promise ,其中包含具有 Object 和 stdout 属性的 stderr 。返回的 ChildProcess 实例作为 child 属性附加到 Promise 。如果发生错误(包括导致退出代码不为0的任何错误),则返回一个被拒绝的承诺,其中包含回调中给出的相同 error 对象,但具有两个附加属性 stdout 和 stderr 。

      const util = require(’node:util’); const execFile = util.promisify(require(’node:child_process’).execFile); async function getVersion() { const { stdout } = await execFile(’node’, [’–version’]); console.log(stdout); } getVersion(); COPY 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. 如果启用了 shell 选项,请勿将未经清理的用户输入传递给此函数。任何包含 shell 元字符的输入都可能用于触发任意命令执行。

      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: 如果启用了 signal 选项,则在相应的 AbortController 上调用 .abort() 类似于在子进程上调用 .kill() ,只是传递给回调的错误将是 AbortError :

      const { execFile } = require(’node:child_process’); const controller = new AbortController(); const { signal } = controller; const child = execFile(’node’, [’–version’], { signal }, (error) => { console.error(error); // an AbortError }); controller.abort(); COPY child_process.fork(modulePath[, args][, options])# History 历史记录 modulePath | The module to run in the child. modulePath | 要在子项中运行的模块。 args <string[]> List of string arguments. args 字符串参数列表。 options cwd | Current working directory of the child process. cwd | 子进程的当前工作目录。 detached Prepare child to run independently of its parent process. Specific behavior depends on the platform, see options.detached). detached 准备子项独立于其父进程运行。具体行为取决于平台,请参阅 options.detached )。 env Environment key-value pairs. Default: process.env. env 环境键值对。默认值: process.env 。 execPath Executable used to create the child process. execPath 用于创建子进程的可执行文件。 execArgv <string[]> List of string arguments passed to the executable. Default: process.execArgv. execArgv 传递给可执行文件的字符串参数列表。默认值: process.execArgv 。 gid Sets the group identity of the process (see setgid(2)). gid 设置进程的组标识(请参阅 setgid(2) )。 serialization Specify the kind of serialization used for sending messages between processes. Possible values are ‘json’ and ‘advanced’. See Advanced serialization for more details. Default: ‘json’. serialization 指定用于在进程之间发送消息的序列化类型。可能的值为 ‘json’ 和 ‘advanced’ 。有关更多详细信息,请参阅高级序列化。默认值: ‘json’ 。 signal Allows closing the child process using an AbortSignal. signal 允许使用 AbortSignal 关闭子进程。 killSignal | The signal value to be used when the spawned process will be killed by timeout or abort signal. Default: ‘SIGTERM’. killSignal | 当生成的进程被超时或中止信号终止时要使用的信号值。默认值: ‘SIGTERM’ 。 silent If true, stdin, stdout, and stderr of the child will be piped to the parent, otherwise they will be inherited from the parent, see the ‘pipe’ and ‘inherit’ options for child_process.spawn()’s stdio for more details. Default: false. silent 如果为 true ,则子进程的标准输入、标准输出和标准错误将被管道传输到父进程,否则它们将从父进程继承,有关更多详细信息,请参阅 ‘pipe’ 和 ‘inherit’ 选项,以了解 child_process.spawn() 的 stdio 。默认值: false 。 stdio | See child_process.spawn()’s stdio. When this option is provided, it overrides silent. If the array variant is used, it must contain exactly one item with value ‘ipc’ or an error will be thrown. For instance [0, 1, 2, ‘ipc’]. stdio <数组> | <字符串> 请参阅 child_process.spawn() 的 stdio 。提供此选项时,它将覆盖 silent 。如果使用数组变体,它必须恰好包含一个值为 ‘ipc’ 的项,否则将引发错误。例如 [0, 1, 2, ‘ipc’] 。 uid Sets the user identity of the process (see setuid(2)). uid <数字> 设置进程的用户标识(请参阅 setuid(2) )。 windowsVerbatimArguments No quoting or escaping of arguments is done on Windows. Ignored on Unix. Default: false. windowsVerbatimArguments <布尔值> 在 Windows 上不引用或转义参数。在 Unix 上忽略。默认值: false 。 timeout In milliseconds the maximum amount of time the process is allowed to run. Default: undefined. timeout <数字> 以毫秒为单位,进程允许运行的最长时间。默认值: undefined 。 Returns: 返回: The child_process.fork() method is a special case of child_process.spawn() used specifically to spawn new Node.js processes. Like child_process.spawn(), a ChildProcess object is returned. The returned ChildProcess will have an additional communication channel built-in that allows messages to be passed back and forth between the parent and child. See subprocess.send() for details. child_process.fork() 方法是 child_process.spawn() 的一种特殊情况,专门用于生成新的 Node.js 进程。与 child_process.spawn() 一样,将返回一个 ChildProcess 对象。返回的 ChildProcess 将具有一个内置的附加通信通道,允许在父进程和子进程之间来回传递消息。有关详细信息,请参阅 subprocess.send() 。

      Keep in mind that spawned Node.js child processes are independent of the parent with exception of the IPC communication channel that is established between the two. Each process has its own memory, with their own V8 instances. Because of the additional resource allocations required, spawning a large number of child Node.js processes is not recommended. 请记住,生成的 Node.js 子进程 独立于父进程,但两者之间建立的 IPC 通信通道除外 。每个进程都有自己的内存,并 their own V8 instances. Because of the additional resource allocations 必需,不建议生成大量子 Node.js 进程。 默认情况下, 将使用父进程的生成新的 Node.js 实例。对象中的属性允许使用备用执行路径。

      By default, child_process.fork() will spawn new Node.js instances using the process.execPath of the parent process. The execPath property in the options object allows for an alternative execution path to be used. 使用自定义 child_process.fork() 启动的 Node.js 进程将使用子进程上的环境变量 process.execPath 标识的文件描述符 (fd) 与父进程通信。

      Node.js processes launched with a custom execPath will communicate with the parent process using the file descriptor (fd) identified using the environment variable NODE_CHANNEL_FD on the child process. 与 execPath POSIX 系统调用不同, NODE_CHANNEL_FD 不会克隆当前进程。

      Unlike the fork(2) POSIX system call, child_process.fork() does not clone the current process. 在 child_process.fork() 中提供的 fork(2) 选项不受支持,如果设置,将被忽略。

      The shell option available in child_process.spawn() is not supported by child_process.fork() and will be ignored if set. 如果启用了 shell 选项,则在相应的 child_process.fork() 上调用 child_process.spawn() 类似于在子进程上调用,只是传递给回调的错误将是:

      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: 历史记录

      if (process.argv[2] === ‘child’) { setTimeout(() => { console.log(Hello from ${process.argv[2]}!); }, 1_000); } else { const { fork } = require(’node:child_process’); const controller = new AbortController(); const { signal } = controller; const child = fork(__filename, [‘child’], { signal }); child.on(’error’, (err) => { // This will be called with err being an AbortError if the controller aborts }); controller.abort(); // Stops the child process } COPY child_process.spawn(command[, args][, options])# History 要运行的命令。 command The command to run. args <string[]> List of string arguments. args 字符串参数列表。 options cwd | Current working directory of the child process. cwd | 子进程的当前工作目录。 env Environment key-value pairs. Default: process.env. env 环境键值对。默认值: process.env 。 argv0 Explicitly set the value of argv[0] sent to the child process. This will be set to command if not specified. argv0 显式设置发送到子进程的 argv[0] 的值。如果未指定,则将其设置为 command 。 stdio | Child’s stdio configuration (see options.stdio). stdio | 子进程的 stdio 配置(请参阅 options.stdio )。 detached Prepare child to run independently of its parent process. Specific behavior depends on the platform, see options.detached). detached 准备子进程独立于其父进程运行。具体行为取决于平台,请参阅 options.detached )。 uid Sets the user identity of the process (see setuid(2)). uid 设置进程的用户标识(请参阅 setuid(2) )。 gid Sets the group identity of the process (see setgid(2)). gid 设置进程的组标识(请参阅 setgid(2) )。 serialization Specify the kind of serialization used for sending messages between processes. Possible values are ‘json’ and ‘advanced’. See Advanced serialization for more details. Default: ‘json’. serialization 指定用于在进程之间发送消息的序列化类型。可能的值为 ‘json’ 和 ‘advanced’ 。有关更多详细信息,请参阅高级序列化。默认值: ‘json’ 。 shell | If true, runs command inside of a shell. Uses ‘/bin/sh’ on Unix, and process.env.ComSpec on Windows. A different shell can be specified as a string. See Shell requirements and Default Windows shell. Default: false (no shell). shell | 如果为 true ,则在 shell 内运行 command 。在 Unix 上使用 ‘/bin/sh’ ,在 Windows 上使用 process.env.ComSpec 。可以将不同的 shell 指定为字符串。请参阅 Shell 要求和默认 Windows shell。默认值: false (无 shell)。 windowsVerbatimArguments No quoting or escaping of arguments is done on Windows. Ignored on Unix. This is set to true automatically when shell is specified and is CMD. Default: false. windowsVerbatimArguments 在 Windows 上不引用或转义参数。在 Unix 上忽略。当指定 shell 并且为 CMD 时,会自动将其设置为 true 。默认值: false 。 windowsHide Hide the subprocess console window that would normally be created on Windows systems. Default: false. windowsHide 隐藏通常在 Windows 系统上创建的子进程控制台窗口。默认值: false . signal allows aborting the child process using an AbortSignal. signal 允许使用 AbortSignal 中止子进程。 timeout In milliseconds the maximum amount of time the process is allowed to run. Default: undefined. timeout 以毫秒为单位,进程允许运行的最长时间。默认值: undefined . killSignal | The signal value to be used when the spawned process will be killed by timeout or abort signal. Default: ‘SIGTERM’. killSignal | 当生成的进程被超时或中止信号终止时要使用的信号值。默认值: ‘SIGTERM’ . Returns: 返回: The child_process.spawn() method spawns a new process using the given command, with command-line arguments in args. If omitted, args defaults to an empty array. 该 child_process.spawn() 方法使用给定的 command 生成一个新进程,其中命令行参数在 args 中。如果省略, args 的默认值为空数组。

      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. 如果启用了 shell 选项,请勿将未经清理的用户输入传递给此函数。任何包含 shell 元字符的输入都可能用于触发任意命令执行。

      A third argument may be used to specify additional options, with these defaults: 可以使用第三个参数指定其他选项,其默认值如下:

      const defaults = { cwd: undefined, env: process.env, }; COPY Use cwd to specify the working directory from which the process is spawned. If not given, the default is to inherit the current working directory. If given, but the path does not exist, the child process emits an ENOENT error and exits immediately. ENOENT is also emitted when the command does not exist. 使用 cwd 指定进程从中派生的工作目录。如果没有给出,则默认继承当前工作目录。如果给出,但路径不存在,则子进程会发出 ENOENT 错误并立即退出。当命令不存在时也会发出 ENOENT 。

      Use env to specify environment variables that will be visible to the new process, the default is process.env. 使用 env 指定新进程可见的环境变量,默认值为 process.env 。

      undefined values in env will be ignored. undefined 中的 env 值将被忽略。

      Example of running ls -lh /usr, capturing stdout, stderr, and the exit code: 运行 ls -lh /usr 的示例,捕获 stdout 、 stderr 和退出代码:

      const { spawn } = require(’node:child_process’); const ls = spawn(’ls’, [’-lh’, ‘/usr’]);

      ls.stdout.on(‘data’, (data) => { console.log(stdout: ${data}); });

      ls.stderr.on(‘data’, (data) => { console.error(stderr: ${data}); });

      ls.on(‘close’, (code) => { console.log(child process exited with code ${code}); }); COPY Example: A very elaborate way to run ps ax | grep ssh 示例:一种非常复杂的方式来运行 ps ax | grep ssh

      const { spawn } = require(’node:child_process’); const ps = spawn(‘ps’, [‘ax’]); const grep = spawn(‘grep’, [‘ssh’]);

      ps.stdout.on(‘data’, (data) => { grep.stdin.write(data); });

      ps.stderr.on(‘data’, (data) => { console.error(ps stderr: ${data}); });

      ps.on(‘close’, (code) => { if (code !== 0) { console.log(ps process exited with code ${code}); } grep.stdin.end(); });

      grep.stdout.on(‘data’, (data) => { console.log(data.toString()); });

      grep.stderr.on(‘data’, (data) => { console.error(grep stderr: ${data}); });

      grep.on(‘close’, (code) => { if (code !== 0) { console.log(grep process exited with code ${code}); } }); COPY Example of checking for failed spawn: 检查失败的 spawn 的示例:

      const { spawn } = require(’node:child_process’); const subprocess = spawn(‘bad_command’);

      subprocess.on(’error’, (err) => { console.error(‘Failed to start subprocess.’); }); COPY Certain platforms (macOS, Linux) will use the value of argv[0] for the process title while others (Windows, SunOS) will use command. 某些平台(macOS、Linux)将使用 argv[0] 的值作为进程标题,而其他平台(Windows、SunOS)将使用 command 。

      Node.js overwrites argv[0] with process.execPath on startup, so process.argv[0] in a Node.js child process will not match the argv0 parameter passed to spawn from the parent. Retrieve it with the process.argv0 property instead. Node.js 在启动时用 process.execPath 覆盖 argv[0] ,因此 Node.js 子进程中的 process.argv[0] 将与从父进程传递给 spawn 的 argv0 参数不匹配。而是使用 process.argv0 属性检索它。

      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: 如果启用了 signal 选项,则对相应的 AbortController 调用 .abort() 类似于对子进程调用 .kill() ,只是传递给回调的错误将是 AbortError :

      const { spawn } = require(’node:child_process’); const controller = new AbortController(); const { signal } = controller; const grep = spawn(‘grep’, [‘ssh’], { signal }); grep.on(’error’, (err) => { // This will be called with err being an AbortError if the controller aborts }); controller.abort(); // Stops the child process COPY options.detached# Added in: v0.7.10 添加于:v0.7.10 On Windows, setting options.detached to true makes it possible for the child process to continue running after the parent exits. The child will have its own console window. Once enabled for a child process, it cannot be disabled. 在 Windows 上,将 options.detached 设置为 true 使子进程在父进程退出后能够继续运行。子进程将拥有自己的控制台窗口。一旦为子进程启用,便无法禁用。

      On non-Windows platforms, if options.detached is set to true, the child process will be made the leader of a new process group and session. Child processes may continue running after the parent exits regardless of whether they are detached or not. See setsid(2) for more information. 在非 Windows 平台上,如果将 options.detached 设置为 true ,子进程将成为新进程组和会话的领导者。无论子进程是否分离,它们都可能在父进程退出后继续运行。有关更多信息,请参阅 setsid(2) 。

      By default, the parent will wait for the detached child to exit. To prevent the parent from waiting for a given subprocess to exit, use the subprocess.unref() method. Doing so will cause the parent’s event loop to not include the child in its reference count, allowing the parent to exit independently of the child, unless there is an established IPC channel between the child and the parent. 默认情况下,父进程将等待分离的子进程退出。若要防止父进程等待给定的 subprocess 退出,请使用 subprocess.unref() 方法。这样做会导致父进程的事件循环不将子进程包含在其引用计数中,从而允许父进程独立于子进程退出,除非子进程和父进程之间建立了 IPC 通道。

      When using the detached option to start a long-running process, the process will not stay running in the background after the parent exits unless it is provided with a stdio configuration that is not connected to the parent. If the parent’s stdio is inherited, the child will remain attached to the controlling terminal. 当使用 detached 选项启动一个长时间运行的进程时,除非为该进程提供未连接到父进程的 stdio 配置,否则该进程在父进程退出后不会在后台继续运行。如果继承了父进程的 stdio ,则子进程将保持连接到控制终端。

      Example of a long-running process, by detaching and also ignoring its parent stdio file descriptors, in order to ignore the parent’s termination: 通过分离并忽略其父 stdio 文件描述符,从而忽略父进程的终止,从而实现长时间运行进程的示例:

      const { spawn } = require(’node:child_process’);

      const subprocess = spawn(process.argv[0], [‘child_program.js’], { detached: true, stdio: ‘ignore’, });

      subprocess.unref(); COPY Alternatively one can redirect the child process’ output into files: 或者,可以将子进程的输出重定向到文件中:

      const fs = require(’node:fs’); const { spawn } = require(’node:child_process’); const out = fs.openSync(’./out.log’, ‘a’); const err = fs.openSync(’./out.log’, ‘a’);

      const subprocess = spawn(‘prg’, [], { detached: true, stdio: [ ‘ignore’, out, err ], });

      subprocess.unref(); COPY options.stdio# History 历史 The options.stdio option is used to configure the pipes that are established between the parent and child process. By default, the child’s stdin, stdout, and stderr are redirected to corresponding subprocess.stdin, subprocess.stdout, and subprocess.stderr streams on the ChildProcess object. This is equivalent to setting the options.stdio equal to [‘pipe’, ‘pipe’, ‘pipe’]. 选项用于配置在父进程和子进程之间建立的管道。默认情况下,子进程的 stdin、stdout 和 stderr 重定向到 ChildProcess 对象上的相应 subprocess.stdin 、 subprocess.stdout 和 subprocess.stderr 流。这相当于将 options.stdio 设置为 [‘pipe’, ‘pipe’, ‘pipe’] 。

      For convenience, options.stdio may be one of the following strings: 为方便起见, options.stdio 可以是以下字符串之一:

      ‘pipe’: equivalent to [‘pipe’, ‘pipe’, ‘pipe’] (the default) ‘pipe’ :相当于 [‘pipe’, ‘pipe’, ‘pipe’] (默认值) ‘overlapped’: equivalent to [‘overlapped’, ‘overlapped’, ‘overlapped’] ‘overlapped’ :相当于 [‘overlapped’, ‘overlapped’, ‘overlapped’] ‘ignore’: equivalent to [‘ignore’, ‘ignore’, ‘ignore’] ‘ignore’ :相当于 [‘ignore’, ‘ignore’, ‘ignore’] ‘inherit’: equivalent to [‘inherit’, ‘inherit’, ‘inherit’] or [0, 1, 2] ‘inherit’ :相当于 [‘inherit’, ‘inherit’, ‘inherit’] 或 [0, 1, 2] Otherwise, the value of options.stdio is an array where each index corresponds to an fd in the child. The fds 0, 1, and 2 correspond to stdin, stdout, and stderr, respectively. Additional fds can be specified to create additional pipes between the parent and child. The value is one of the following: 否则, options.stdio 的值是一个数组,其中每个索引对应子进程中的一个 fd。fd 0、1 和 2 分别对应 stdin、stdout 和 stderr。可以指定其他 fd 以在父进程和子进程之间创建其他管道。值是以下之一:

      ‘pipe’: Create a pipe between the child process and the parent process. The parent end of the pipe is exposed to the parent as a property on the child_process object as subprocess.stdio[fd]. Pipes created for fds 0, 1, and 2 are also available as subprocess.stdin, subprocess.stdout and subprocess.stderr, respectively. These are not actual Unix pipes and therefore the child process can not use them by their descriptor files, e.g. /dev/fd/2 or /dev/stdout. ‘pipe’ :在子进程和父进程之间创建一个管道。管道的父端作为 child_process 对象的属性 subprocess.stdio[fd] 暴露给父进程。为文件描述符 0、1 和 2 创建的管道也分别可用作 subprocess.stdin 、 subprocess.stdout 和 subprocess.stderr 。这些不是实际的 Unix 管道,因此子进程无法通过其描述符文件(例如 /dev/fd/2 或 /dev/stdout )使用它们。

      ‘overlapped’: Same as ‘pipe’ except that the FILE_FLAG_OVERLAPPED flag is set on the handle. This is necessary for overlapped I/O on the child process’s stdio handles. See the docs for more details. This is exactly the same as ‘pipe’ on non-Windows systems. ‘overlapped’ :与 ‘pipe’ 相同,但 FILE_FLAG_OVERLAPPED 标志在句柄上设置。这对于子进程的 stdio 句柄上的重叠 I/O 是必需的。有关更多详细信息,请参阅文档。在非 Windows 系统上,这与 ‘pipe’ 完全相同。

      ‘ipc’: Create an IPC channel for passing messages/file descriptors between parent and child. A ChildProcess may have at most one IPC stdio file descriptor. Setting this option enables the subprocess.send() method. If the child is a Node.js process, the presence of an IPC channel will enable process.send() and process.disconnect() methods, as well as ‘disconnect’ and ‘message’ events within the child. ‘ipc’ :创建一个 IPC 通道,用于在父进程和子进程之间传递消息/文件描述符。一个 ChildProcess 最多可以有一个 IPC stdio 文件描述符。设置此选项将启用 subprocess.send() 方法。如果子进程是 Node.js 进程,则 IPC 通道将启用 process.send() 和 process.disconnect() 方法,以及子进程中的 ‘disconnect’ 和 ‘message’ 事件。

      Accessing the IPC channel fd in any way other than process.send() or using the IPC channel with a child process that is not a Node.js instance is not supported. 以除 process.send() 之外的任何方式访问 IPC 通道 fd 或使用 IPC 通道与不是 Node.js 实例的子进程通信不受支持。

      ‘ignore’: Instructs Node.js to ignore the fd in the child. While Node.js will always open fds 0, 1, and 2 for the processes it spawns, setting the fd to ‘ignore’ will cause Node.js to open /dev/null and attach it to the child’s fd. ‘ignore’ :指示 Node.js 忽略子进程中的 fd。虽然 Node.js 始终会为其生成的进程打开 fd 0、1 和 2,但将 fd 设置为 ‘ignore’ 将导致 Node.js 打开 /dev/null 并将其附加到子进程的 fd。

      ‘inherit’: Pass through the corresponding stdio stream to/from the parent process. In the first three positions, this is equivalent to process.stdin, process.stdout, and process.stderr, respectively. In any other position, equivalent to ‘ignore’. ‘inherit’ :将相应的 stdio 流传递到父进程或从父进程传递。在前三个位置,这分别等同于 process.stdin 、 process.stdout 和 process.stderr 。在任何其他位置,等同于 ‘ignore’ 。

      object: Share a readable or writable stream that refers to a tty, file, socket, or a pipe with the child process. The stream’s underlying file descriptor is duplicated in the child process to the fd that corresponds to the index in the stdio array. The stream must have an underlying descriptor (file streams do not until the ‘open’ event has occurred). 对象:共享一个可读或可写的流,该流引用 tty、文件、套接字或与子进程的管道。流的基础文件描述符在子进程中复制到对应于 stdio 数组中索引的 fd。该流必须具有基础描述符(文件流在 ‘open’ 事件发生之前没有)。

      Positive integer: The integer value is interpreted as a file descriptor that is open in the parent process. It is shared with the child process, similar to how objects can be shared. Passing sockets is not supported on Windows. 正整数:整数值解释为在父进程中打开的文件描述符。它与子进程共享,类似于共享 对象的方式。在 Windows 上不支持传递套接字。

      null, undefined: Use default value. For stdio fds 0, 1, and 2 (in other words, stdin, stdout, and stderr) a pipe is created. For fd 3 and up, the default is ‘ignore’. null 、 undefined :使用默认值。对于 stdio fd 0、1 和 2(换句话说,stdin、stdout 和 stderr),将创建一个管道。对于 fd 3 及以上,默认值为 ‘ignore’ 。

      const { spawn } = require(’node:child_process’);

      // Child will use parent’s stdios. spawn(‘prg’, [], { stdio: ‘inherit’ });

      // Spawn child sharing only stderr. spawn(‘prg’, [], { stdio: [‘pipe’, ‘pipe’, process.stderr] });

      // Open an extra fd=4, to interact with programs presenting a // startd-style interface. spawn(‘prg’, [], { stdio: [‘pipe’, null, null, null, ‘pipe’] }); COPY It is worth noting that when an IPC channel is established between the parent and child processes, and the child is a Node.js process, the child is launched with the IPC channel unreferenced (using unref()) until the child registers an event handler for the ‘disconnect’ event or the ‘message’ event. This allows the child to exit normally without the process being held open by the open IPC channel. 值得注意的是,当在父进程和子进程之间建立 IPC 通道,并且子进程是 Node.js 进程时,子进程使用 IPC 通道启动,直到子进程为 ‘disconnect’ 事件或 ‘message’ 事件注册事件处理程序或使用 unref() 取消引用 IPC 通道。这允许子进程正常退出,而不会因打开的 IPC 通道而使进程保持打开状态。

      On Unix-like operating systems, the child_process.spawn() method performs memory operations synchronously before decoupling the event loop from the child. Applications with a large memory footprint may find frequent child_process.spawn() calls to be a bottleneck. For more information, see V8 issue 7381. 在类 Unix 操作系统上, child_process.spawn() 方法在从子进程中分离事件循环之前同步执行内存操作。具有大量内存占用空间的应用程序可能会发现频繁的 child_process.spawn() 调用是一个瓶颈。有关更多信息,请参阅 V8 问题 7381。

      See also: child_process.exec() and child_process.fork(). 另请参阅: child_process.exec() 和 child_process.fork() 。

      Synchronous process creation 同步进程创建# The child_process.spawnSync(), child_process.execSync(), and child_process.execFileSync() methods are synchronous and will block the Node.js event loop, pausing execution of any additional code until the spawned process exits. child_process.spawnSync() 、 child_process.execSync() 和 child_process.execFileSync() 方法是同步的,并且会阻塞 Node.js 事件循环,暂停执行任何其他代码,直到生成的进程退出。

      Blocking calls like these are mostly useful for simplifying general-purpose scripting tasks and for simplifying the loading/processing of application configuration at startup. 像这些阻塞调用主要用于简化通用 脚本任务,以及简化应用程序 配置在启动时的加载/处理。

      child_process.execFileSync(file[, args][, options])# History 历史 file The name or path of the executable file to run. file 要运行的可执行文件的名称或路径。 args <string[]> List of string arguments. args 字符串参数列表。 options cwd | Current working directory of the child process. cwd | 子进程的当前工作目录。 input | | | The value which will be passed as stdin to the spawned process. If stdio[0] is set to ‘pipe’, Supplying this value will override stdio[0]. input | | | 将作为标准输入传递给派生进程的值。如果将 stdio[0] 设置为 ‘pipe’ ,提供此值将覆盖 stdio[0] 。 stdio | Child’s stdio configuration. stderr by default will be output to the parent process’ stderr unless stdio is specified. Default: ‘pipe’. stdio | 子进程的 stdio 配置。默认情况下, stderr 将输出到父进程的 stderr,除非指定了 stdio 。默认值: ‘pipe’ 。 env Environment key-value pairs. Default: process.env. env 环境键值对。默认值: process.env 。 uid Sets the user identity of the process (see setuid(2)). uid 设置进程的用户标识(请参阅 setuid(2) )。 gid Sets the group identity of the process (see setgid(2)). gid 设置进程的组标识(请参阅 setgid(2) )。 timeout In milliseconds the maximum amount of time the process is allowed to run. Default: undefined. timeout 以毫秒为单位,进程允许运行的最长时间。默认值: undefined 。 killSignal | The signal value to be used when the spawned process will be killed. Default: ‘SIGTERM’. killSignal | 派生进程被终止时要使用的信号值。默认值: ‘SIGTERM’ 。 maxBuffer Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated. See caveat at maxBuffer and Unicode. Default: 1024 * 1024. maxBuffer stdout 或 stderr 上允许的最大数据量(以字节为单位)。如果超过,则终止子进程。请参阅 maxBuffer 和 Unicode 中的注意事项。默认值: 1024 * 1024 。 encoding The encoding used for all stdio inputs and outputs. Default: ‘buffer’. encoding 用于所有 stdio 输入和输出的编码。默认值: ‘buffer’ 。 windowsHide Hide the subprocess console window that would normally be created on Windows systems. Default: false. windowsHide 隐藏通常在 Windows 系统上创建的子进程控制台窗口。默认值: false 。 shell | If true, runs command inside of a shell. Uses ‘/bin/sh’ on Unix, and process.env.ComSpec on Windows. A different shell can be specified as a string. See Shell requirements and Default Windows shell. Default: false (no shell). shell | 如果为 true ,则在 shell 内运行 command 。在 Unix 上使用 ‘/bin/sh’ ,在 Windows 上使用 process.env.ComSpec 。可以将不同的 shell 指定为字符串。请参阅 Shell 要求和默认 Windows shell。默认值: false (无 shell)。 Returns: | The stdout from the command. 返回: | 命令的 stdout。 The child_process.execFileSync() method is generally identical to child_process.execFile() with the exception that the method will not return until the child process has fully closed. When a timeout has been encountered and killSignal is sent, the method won’t return until the process has completely exited. child_process.execFileSync() 方法通常与 child_process.execFile() 相同,但该方法在子进程完全关闭之前不会返回。遇到超时并发送 killSignal 时,该方法在进程完全退出之前不会返回。

      If the child process intercepts and handles the SIGTERM signal and does not exit, the parent process will still wait until the child process has exited. 如果子进程拦截并处理 SIGTERM 信号且不退出,父进程仍会等到子进程退出。

      If the process times out or has a non-zero exit code, this method will throw an Error that will include the full result of the underlying child_process.spawnSync(). 如果进程超时或具有非零退出代码,此方法将抛出 Error ,其中将包括基础 child_process.spawnSync() 的完整结果。

      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. 如果启用了 shell 选项,请勿将未经清理的用户输入传递给此函数。任何包含 shell 元字符的输入都可能用于触发任意命令执行。

      child_process.execSync(command[, options])# History 历史 command The command to run. command 要运行的命令。 options cwd | Current working directory of the child process. cwd | 子进程的当前工作目录。 input | | | The value which will be passed as stdin to the spawned process. If stdio[0] is set to ‘pipe’, Supplying this value will override stdio[0]. input | | | 将作为标准输入传递给已生成的进程的值。如果将 stdio[0] 设置为 ‘pipe’ ,提供此值将覆盖 stdio[0] 。 stdio | Child’s stdio configuration. stderr by default will be output to the parent process’ stderr unless stdio is specified. Default: ‘pipe’. stdio | 子进程的 stdio 配置。默认情况下, stderr 会输出到父进程的 stderr,除非指定了 stdio 。默认值: ‘pipe’ 。 env Environment key-value pairs. Default: process.env. env 环境键值对。默认值: process.env 。 shell Shell to execute the command with. See Shell requirements and Default Windows shell. Default: ‘/bin/sh’ on Unix, process.env.ComSpec on Windows. shell 用于执行命令的 Shell。请参阅 Shell 要求和默认 Windows Shell。默认值:Unix 上的 ‘/bin/sh’ ,Windows 上的 process.env.ComSpec 。 uid Sets the user identity of the process. (See setuid(2)). uid 设置进程的用户标识。(请参阅 setuid(2) )。 gid Sets the group identity of the process. (See setgid(2)). gid 设置进程的组标识。(请参阅 setgid(2) )。 timeout In milliseconds the maximum amount of time the process is allowed to run. Default: undefined. timeout 以毫秒为单位,进程允许运行的最长时间。默认值: undefined 。 killSignal | The signal value to be used when the spawned process will be killed. Default: ‘SIGTERM’. killSignal | 在生成的进程被终止时要使用的信号值。默认值: ‘SIGTERM’ 。 maxBuffer 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 at maxBuffer and Unicode. Default: 1024 * 1024. maxBuffer stdout 或 stderr 上允许的最大数据量(以字节为单位)。如果超出,则终止子进程并截断任何输出。请参阅 maxBuffer 和 Unicode 中的注意事项。默认值: 1024 * 1024 . encoding The encoding used for all stdio inputs and outputs. Default: ‘buffer’. encoding 用于所有 stdio 输入和输出的编码。默认值: ‘buffer’ . windowsHide Hide the subprocess console window that would normally be created on Windows systems. Default: false. windowsHide 隐藏通常在 Windows 系统上创建的子进程控制台窗口。默认值: false . Returns: | The stdout from the command. 返回: | 命令的 stdout。 The child_process.execSync() method is generally identical to child_process.exec() with the exception that the method will not return until the child process has fully closed. When a timeout has been encountered and killSignal is sent, the method won’t return until the process has completely exited. If the child process intercepts and handles the SIGTERM signal and doesn’t exit, the parent process will wait until the child process has exited. 除了方法不会返回,直到子进程完全关闭之外, child_process.execSync() 方法通常与 child_process.exec() 相同。当遇到超时并且发送 killSignal 时,该方法不会返回,直到进程完全退出。如果子进程拦截并处理 SIGTERM 信号并且不退出,则父进程将等待,直到子进程退出。

      If the process times out or has a non-zero exit code, this method will throw. The Error object will contain the entire result from child_process.spawnSync(). 如果进程超时或具有非零退出代码,则此方法将引发异常。 Error 对象将包含 child_process.spawnSync() 的整个结果。

      Never pass unsanitized user input to this function. Any input containing shell metacharacters may be used to trigger arbitrary command execution. 切勿将未经清理的用户输入传递给此函数。任何包含 shell 元字符的输入都可能用于触发任意命令执行。

      child_process.spawnSync(command[, args][, options])# History 历史 command The command to run. command 要运行的命令。 args <string[]> List of string arguments. args 字符串参数列表。 options cwd | Current working directory of the child process. cwd | 子进程的当前工作目录。 input | | | The value which will be passed as stdin to the spawned process. If stdio[0] is set to ‘pipe’, Supplying this value will override stdio[0]. input | | | 将作为标准输入传递给派生进程的值。如果将 stdio[0] 设置为 ‘pipe’ ,提供此值将覆盖 stdio[0] 。 argv0 Explicitly set the value of argv[0] sent to the child process. This will be set to command if not specified. argv0 显式设置发送给子进程的 argv[0] 的值。如果未指定,则将其设置为 command 。 stdio | Child’s stdio configuration. Default: ‘pipe’. stdio | 子进程的 stdio 配置。默认值: ‘pipe’ 。 env Environment key-value pairs. Default: process.env. env 环境键值对。默认值: process.env 。 uid Sets the user identity of the process (see setuid(2)). uid 设置进程的用户标识(请参阅 setuid(2) )。 gid Sets the group identity of the process (see setgid(2)). gid 设置进程的组标识(请参阅 setgid(2) )。 timeout In milliseconds the maximum amount of time the process is allowed to run. Default: undefined. timeout 以毫秒为单位,进程允许运行的最长时间。默认值: undefined 。 killSignal | The signal value to be used when the spawned process will be killed. Default: ‘SIGTERM’. killSignal | 在派生进程被终止时要使用的信号值。默认值: ‘SIGTERM’ 。 maxBuffer 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 at maxBuffer and Unicode. Default: 1024 * 1024. maxBuffer stdout 或 stderr 上允许的最大数据量(以字节为单位)。如果超出,则终止子进程并截断任何输出。请参阅 maxBuffer 和 Unicode 中的注意事项。默认值: 1024 * 1024 . encoding The encoding used for all stdio inputs and outputs. Default: ‘buffer’. encoding 用于所有 stdio 输入和输出的编码。默认值: ‘buffer’ . shell | If true, runs command inside of a shell. Uses ‘/bin/sh’ on Unix, and process.env.ComSpec on Windows. A different shell can be specified as a string. See Shell requirements and Default Windows shell. Default: false (no shell). shell | 如果为 true ,则在 shell 内运行 command 。在 Unix 上使用 ‘/bin/sh’ ,在 Windows 上使用 process.env.ComSpec 。可以将不同的 shell 指定为字符串。请参阅 Shell 要求和默认 Windows shell。默认值: false (无 shell)。 windowsVerbatimArguments No quoting or escaping of arguments is done on Windows. Ignored on Unix. This is set to true automatically when shell is specified and is CMD. Default: false. windowsVerbatimArguments 在 Windows 上不引用或转义参数。在 Unix 上忽略。当指定 shell 且为 CMD 时,此项会自动设置为 true 。默认值: false . windowsHide Hide the subprocess console window that would normally be created on Windows systems. Default: false. windowsHide 隐藏通常在 Windows 系统上创建的子进程控制台窗口。默认值: false . Returns: 返回: pid Pid of the child process. pid 子进程的 Pid。 output Array of results from stdio output. output stdio 输出的结果数组。 stdout | The contents of output[1]. stdout | output[1] 的内容。 stderr | The contents of output[2]. stderr | output[2] 的内容。 status | The exit code of the subprocess, or null if the subprocess terminated due to a signal. status | 子进程的退出代码,或 null 如果子进程因信号而终止。 signal | The signal used to kill the subprocess, or null if the subprocess did not terminate due to a signal. signal | 用于终止子进程的信号,或 null 如果子进程不是因信号而终止。 error The error object if the child process failed or timed out. error 如果子进程失败或超时,则为错误对象。 The child_process.spawnSync() method is generally identical to child_process.spawn() with the exception that the function will not return until the child process has fully closed. When a timeout has been encountered and killSignal is sent, the method won’t return until the process has completely exited. If the process intercepts and handles the SIGTERM signal and doesn’t exit, the parent process will wait until the child process has exited. 除了函数在子进程完全关闭之前不会返回之外, child_process.spawnSync() 方法通常与 child_process.spawn() 相同。当遇到超时并发送 killSignal 时,该方法在进程完全退出之前不会返回。如果进程拦截并处理 SIGTERM 信号且不退出,则父进程将等到子进程退出。

      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. 如果启用了 shell 选项,请勿将未经清理的用户输入传递给此函数。任何包含 shell 元字符的输入都可能用于触发任意命令执行。

      Class: ChildProcess 类: ChildProcess# Added in: v2.2.0 添加于:v2.2.0 Extends: 扩展: Instances of the ChildProcess represent spawned child processes. ChildProcess 的实例表示已生成的子进程。

      Instances of ChildProcess are not intended to be created directly. Rather, use the child_process.spawn(), child_process.exec(), child_process.execFile(), or child_process.fork() methods to create instances of ChildProcess. ChildProcess 的实例不打算直接创建。相反,使用 child_process.spawn() 、 child_process.exec() 、 child_process.execFile() 或 child_process.fork() 方法创建 ChildProcess 的实例。

      Event: ‘close’ 事件: ‘close’# Added in: v0.7.7 添加于:v0.7.7 code The exit code if the child exited on its own. code 如果子进程自行退出,则退出代码。 signal The signal by which the child process was terminated. signal 子进程被终止的信号。 The ‘close’ event is emitted after a process has ended and the stdio streams of a child process have been closed. This is distinct from the ’exit’ event, since multiple processes might share the same stdio streams. The ‘close’ event will always emit after ’exit’ was already emitted, or ’error’ if the child failed to spawn. 在进程结束并且子进程的 stdio 流已关闭后,会发出 ‘close’ 事件。这与 ’exit’ 事件不同,因为多个进程可能共享相同的 stdio 流。如果已发出 ’exit’ ,或者子进程无法生成,则 ‘close’ 事件始终会发出 ’error’ 。

      const { spawn } = require(’node:child_process’); const ls = spawn(’ls’, [’-lh’, ‘/usr’]);

      ls.stdout.on(‘data’, (data) => { console.log(stdout: ${data}); });

      ls.on(‘close’, (code) => { console.log(child process close all stdio with code ${code}); });

      ls.on(’exit’, (code) => { console.log(child process exited with code ${code}); }); COPY Event: ‘disconnect’ 事件: ‘disconnect’# Added in: v0.7.2 添加于:v0.7.2 The ‘disconnect’ event is emitted after calling the subprocess.disconnect() method in parent process or process.disconnect() in child process. After disconnecting it is no longer possible to send or receive messages, and the subprocess.connected property is false. 在父进程中调用 subprocess.disconnect() 方法或在子进程中调用 process.disconnect() 方法后,会发出 ‘disconnect’ 事件。断开连接后,将无法再发送或接收消息,并且 subprocess.connected 属性为 false 。

      Event: ’error’ 事件: ’error’# err The error. err 错误。 The ’error’ event is emitted whenever: 无论何时,都会发出 ’error’ 事件:

      The process could not be spawned. 无法生成进程。 The process could not be killed. 无法终止进程。 Sending a message to the child process failed. 向子进程发送消息失败。 The child process was aborted via the signal option. 通过 signal 选项中止子进程。 The ’exit’ event may or may not fire after an error has occurred. When listening to both the ’exit’ and ’error’ events, guard against accidentally invoking handler functions multiple times. 在发生错误后, ’exit’ 事件可能会触发,也可能不会触发。在同时监听 ’exit’ 和 ’error’ 事件时,防止意外多次调用处理程序函数。

      See also subprocess.kill() and subprocess.send(). 另请参阅 subprocess.kill() 和 subprocess.send() 。

      Event: ’exit’ 事件: ’exit’# Added in: v0.1.90 添加于:v0.1.90 code The exit code if the child exited on its own. code 如果子进程自行退出,则为退出代码。 signal The signal by which the child process was terminated. signal 子进程被终止的信号。 The ’exit’ event is emitted after the child process ends. If the process exited, code is the final exit code of the process, otherwise null. If the process terminated due to receipt of a signal, signal is the string name of the signal, otherwise null. One of the two will always be non-null. ’exit’ 事件在子进程结束后触发。如果进程退出,则 code 是进程的最终退出代码,否则为 null 。如果进程因收到信号而终止,则 signal 是信号的字符串名称,否则为 null 。两者之一始终为非 null 。

      When the ’exit’ event is triggered, child process stdio streams might still be open. 当触发 ’exit’ 事件时,子进程 stdio 流可能仍然处于打开状态。

      Node.js establishes signal handlers for SIGINT and SIGTERM and Node.js processes will not terminate immediately due to receipt of those signals. Rather, Node.js will perform a sequence of cleanup actions and then will re-raise the handled signal. Node.js 为 SIGINT 和 SIGTERM 建立信号处理程序,并且 Node.js 进程不会因收到这些信号而立即终止。相反,Node.js 将执行一系列清理操作,然后重新引发已处理的信号。

      See waitpid(2). 请参阅 waitpid(2) 。

      Event: ‘message’ 事件: ‘message’# Added in: v0.5.9 添加于:v0.5.9 message A parsed JSON object or primitive value. message 已解析的 JSON 对象或原始值。 sendHandle A net.Socket or net.Server object, or undefined. sendHandle A net.Socket 或 net.Server 对象,或未定义。 The ‘message’ event is triggered when a child process uses process.send() to send messages. 当子进程使用 process.send() 发送消息时,会触发 ‘message’ 事件。

      The message goes through serialization and parsing. The resulting message might not be the same as what is originally sent. 消息会经过序列化和解析。生成的 消息可能与最初发送的消息不同。

      If the serialization option was set to ‘advanced’ used when spawning the child process, the message argument can contain data that JSON is not able to represent. See Advanced serialization for more details. 如果在生成子进程时将 serialization 选项设置为 ‘advanced’ ,则 message 参数可以包含 JSON 无法表示的数据。有关更多详细信息,请参阅高级序列化。

      Event: ‘spawn’ 事件: ‘spawn’# Added in: v15.1.0, v14.17.0 添加于:v15.1.0、v14.17.0 The ‘spawn’ event is emitted once the child process has spawned successfully. If the child process does not spawn successfully, the ‘spawn’ event is not emitted and the ’error’ event is emitted instead. 子进程成功生成后,将发出 ‘spawn’ 事件。如果子进程未成功生成,则不会发出 ‘spawn’ 事件,而是发出 ’error’ 事件。

      If emitted, the ‘spawn’ event comes before all other events and before any data is received via stdout or stderr. 如果发出,则 ‘spawn’ 事件在所有其他事件之前发出,并且在通过 stdout 或 stderr 接收任何数据之前发出。

      The ‘spawn’ event will fire regardless of whether an error occurs within the spawned process. For example, if bash some-command spawns successfully, the ‘spawn’ event will fire, though bash may fail to spawn some-command. This caveat also applies when using { shell: true }. ‘spawn’ 事件将触发,无论在生成的进程中是否发生错误。例如,如果 bash some-command 成功生成,则 ‘spawn’ 事件将触发,尽管 bash 可能无法生成 some-command 。使用 { shell: true } 时,此警告也适用。

      subprocess.channel# History 历史记录 A pipe representing the IPC channel to the child process. 表示到子进程的 IPC 通道的管道。 The subprocess.channel property is a reference to the child’s IPC channel. If no IPC channel exists, this property is undefined. 属性 subprocess.channel 是对子进程 IPC 通道的引用。如果不存在 IPC 通道,则此属性为 undefined 。

      subprocess.channel.ref()# Added in: v7.1.0 添加于:v7.1.0 This method makes the IPC channel keep the event loop of the parent process running if .unref() has been called before. 如果在调用 .unref() 之前已调用此方法,则 IPC 通道会让父进程的事件循环保持运行。

      subprocess.channel.unref()# Added in: v7.1.0 添加于:v7.1.0 This method makes the IPC channel not keep the event loop of the parent process running, and lets it finish even while the channel is open. 此方法让 IPC 通道不保持父进程的事件循环 运行,并允许它在通道打开时完成。

      subprocess.connected# Added in: v0.7.2 添加于:v0.7.2 Set to false after subprocess.disconnect() is called. 在调用 subprocess.disconnect() 后设置为 false 。 The subprocess.connected property indicates whether it is still possible to send and receive messages from a child process. When subprocess.connected is false, it is no longer possible to send or receive messages. 属性 subprocess.connected 指示是否仍可以向子进程发送和接收消息。当 subprocess.connected 为 false 时,将无法再发送或接收消息。

      subprocess.disconnect()# Added in: v0.7.2 添加于:v0.7.2 Closes the IPC channel between parent and child, allowing the child to exit gracefully once there are no other connections keeping it alive. After calling this method the subprocess.connected and process.connected properties in both the parent and child (respectively) will be set to false, and it will be no longer possible to pass messages between the processes. 关闭父进程和子进程之间的 IPC 通道,允许子进程在没有其他连接使其保持活动状态时正常退出。调用此方法后,父进程和子进程(分别)中的 subprocess.connected 和 process.connected 属性将设置为 false ,并且将无法在进程之间传递消息。

      The ‘disconnect’ event will be emitted when there are no messages in the process of being received. This will most often be triggered immediately after calling subprocess.disconnect(). 当没有正在接收的消息时,将发出 ‘disconnect’ 事件。这通常会在调用 subprocess.disconnect() 后立即触发。

      When the child process is a Node.js instance (e.g. spawned using child_process.fork()), the process.disconnect() method can be invoked within the child process to close the IPC channel as well. 当子进程是 Node.js 实例(例如使用 child_process.fork() 生成的)时,可以在子进程中调用 process.disconnect() 方法以关闭 IPC 通道。

      subprocess.exitCode# The subprocess.exitCode property indicates the exit code of the child process. If the child process is still running, the field will be null. subprocess.exitCode 属性指示子进程的退出代码。如果子进程仍在运行,该字段将为 null 。

      subprocess.kill([signal])# Added in: v0.1.90 signal | Returns: 返回: The subprocess.kill() method sends a signal to the child process. If no argument is given, the process will be sent the ‘SIGTERM’ signal. See signal(7) for a list of available signals. This function returns true if kill(2) succeeds, and false otherwise. 方法向子进程发送信号。如果未给出参数,则会向进程发送 ‘SIGTERM’ 信号。有关可用信号的列表,请参阅 signal(7) 。如果 kill(2) 成功,此函数将返回 true ,否则返回 false 。

      const { spawn } = require(’node:child_process’); const grep = spawn(‘grep’, [‘ssh’]);

      grep.on(‘close’, (code, signal) => { console.log( child process terminated due to receipt of signal ${signal}); });

      // Send SIGHUP to process. grep.kill(‘SIGHUP’); COPY The ChildProcess object may emit an ’error’ event if the signal cannot be delivered. Sending a signal to a child process that has already exited is not an error but may have unforeseen consequences. Specifically, if the process identifier (PID) has been reassigned to another process, the signal will be delivered to that process instead which can have unexpected results. 如果无法传递信号,则 ChildProcess 对象可能会发出 ’error’ 事件。向已退出的子进程发送信号并非错误,但可能会产生无法预见的后果。具体来说,如果进程标识符 (PID) 已重新分配给另一个进程,则信号将传递给该进程,从而可能产生意外结果。

      While the function is called kill, the signal delivered to the child process may not actually terminate the process. 当调用函数 kill 时,传递给子进程的信号可能不会实际终止该进程。

      See kill(2) for reference. 有关参考,请参见 kill(2) 。

      On Windows, where POSIX signals do not exist, the signal argument will be ignored, and the process will be killed forcefully and abruptly (similar to ‘SIGKILL’). See Signal Events for more details. 在 POSIX 信号不存在的 Windows 上,将忽略 signal 参数,并且进程将被强制且突然终止(类似于 ‘SIGKILL’ )。有关更多详细信息,请参阅信号事件。

      On Linux, child processes of child processes will not be terminated when attempting to kill their parent. This is likely to happen when running a new process in a shell or with the use of the shell option of ChildProcess: 在 Linux 上,尝试终止父进程时,子进程的子进程不会被终止。这很可能发生在 shell 中运行新进程或使用 ChildProcess 的 shell 选项时:

      ‘use strict’; const { spawn } = require(’node:child_process’);

      const subprocess = spawn( ‘sh’, [ ‘-c’, node -e "setInterval(() => { console.log(process.pid, 'is alive') }, 500);", ], { stdio: [‘inherit’, ‘inherit’, ‘inherit’], }, );

      setTimeout(() => { subprocess.kill(); // Does not terminate the Node.js process in the shell. }, 2000); COPY subprocessSymbol.dispose# Added in: v20.5.0, v18.18.0 添加于:v20.5.0、v18.18.0 Stability: 1 - Experimental 稳定性:1 - 实验性 Calls subprocess.kill() with ‘SIGTERM’. 使用 ‘SIGTERM’ 调用 subprocess.kill() 。

      subprocess.killed# Added in: v0.5.10 添加于:v0.5.10 Set to true after subprocess.kill() is used to successfully send a signal to the child process. 在使用 subprocess.kill() 成功向子进程发送信号后设置为 true 。 The subprocess.killed property indicates whether the child process successfully received a signal from subprocess.kill(). The killed property does not indicate that the child process has been terminated. subprocess.killed 属性指示子进程是否成功从 subprocess.kill() 接收信号。 killed 属性并不表示子进程已终止。

      subprocess.pid# Added in: v0.1.90 | Returns the process identifier (PID) of the child process. If the child process fails to spawn due to errors, then the value is undefined and error is emitted. 返回子进程的进程标识符 (PID)。如果子进程由于错误而无法派生,则值为 undefined 并发出 error 。

      const { spawn } = require(’node:child_process’); const grep = spawn(‘grep’, [‘ssh’]);

      console.log(Spawned child pid: ${grep.pid}); grep.stdin.end(); COPY subprocess.ref()# Added in: v0.7.10 添加于:v0.7.10 Calling subprocess.ref() after making a call to subprocess.unref() will restore the removed reference count for the child process, forcing the parent to wait for the child to exit before exiting itself. 在调用 subprocess.unref() 后调用 subprocess.ref() 将恢复已删除的子进程引用计数,从而强制父进程等待子进程退出后再退出自身。

      const { spawn } = require(’node:child_process’);

      const subprocess = spawn(process.argv[0], [‘child_program.js’], { detached: true, stdio: ‘ignore’, });

      subprocess.unref(); subprocess.ref(); COPY subprocess.send(message[, sendHandle[, options]][, callback])# History 要运行的命令。 message sendHandle options The options argument, if present, is an object used to parameterize the sending of certain types of handles. options supports the following properties: options 如果存在, options 参数是一个用于对某些类型的句柄的发送进行参数化的对象。 options 支持以下属性: keepOpen A value that can be used when passing instances of net.Socket. When true, the socket is kept open in the sending process. Default: false. keepOpen 在传递 net.Socket 的实例时可以使用的一个值。当 true 时,套接字在发送过程中保持打开。默认值: false 。 callback callback <函数> Returns: 返回: When an IPC channel has been established between the parent and child ( i.e. when using child_process.fork()), the subprocess.send() method can be used to send messages to the child process. When the child process is a Node.js instance, these messages can be received via the ‘message’ event. 当父进程和子进程之间建立 IPC 通道(即使用 child_process.fork() 时),可以使用 subprocess.send() 方法向子进程发送消息。当子进程是 Node.js 实例时,可以通过 ‘message’ 事件接收这些消息。

      The message goes through serialization and parsing. The resulting message might not be the same as what is originally sent. 消息会经过序列化和解析。生成的 消息可能与最初发送的消息不同。

      For example, in the parent script: 例如,在父脚本中:

      const cp = require(’node:child_process’); const n = cp.fork(${__dirname}/sub.js);

      n.on(‘message’, (m) => { console.log(‘PARENT got message:’, m); });

      // Causes the child to print: CHILD got message: { hello: ‘world’ } n.send({ hello: ‘world’ }); COPY And then the child script, ‘sub.js’ might look like this: 然后子脚本 ‘sub.js’ 可能如下所示:

      process.on(‘message’, (m) => { console.log(‘CHILD got message:’, m); });

      // Causes the parent to print: PARENT got message: { foo: ‘bar’, baz: null } process.send({ foo: ‘bar’, baz: NaN }); COPY Child Node.js processes will have a process.send() method of their own that allows the child to send messages back to the parent. 子 Node.js 进程将有自己的 process.send() 方法,允许子进程向父进程发送消息。

      There is a special case when sending a {cmd: ‘NODE_foo’} message. Messages containing a NODE_ prefix in the cmd property are reserved for use within Node.js core and will not be emitted in the child’s ‘message’ event. Rather, such messages are emitted using the ‘internalMessage’ event and are consumed internally by Node.js. Applications should avoid using such messages or listening for ‘internalMessage’ events as it is subject to change without notice. 在发送 {cmd: ‘NODE_foo’} 消息时有一个特殊情况。在 cmd 属性中包含 NODE_ 前缀的消息专用于 Node.js 核心内部使用,不会在子进程的 ‘message’ 事件中发出。相反,此类消息使用 ‘internalMessage’ 事件发出,并由 Node.js 内部使用。应用程序应避免使用此类消息或侦听 ‘internalMessage’ 事件,因为此类消息可能会在不经通知的情况下发生更改。

      The optional sendHandle argument that may be passed to subprocess.send() is for passing a TCP server or socket object to the child process. The child will receive the object as the second argument passed to the callback function registered on the ‘message’ event. Any data that is received and buffered in the socket will not be sent to the child. 可以传递给 subprocess.send() 的可选 sendHandle 参数用于将 TCP 服务器或套接字对象传递给子进程。子进程会将该对象作为传递给在 ‘message’ 事件上注册的回调函数的第二个参数来接收。套接字中接收并缓冲的任何数据都不会发送给子进程。

      The optional callback is a function that is invoked after the message is sent but before the child may have received it. The function is called with a single argument: null on success, or an Error object on failure. 可选的 callback 是在发送消息后但在子进程可能已收到消息之前调用的函数。该函数使用单个参数调用:成功时为 null ,失败时为 Error 对象。

      If no callback function is provided and the message cannot be sent, an ’error’ event will be emitted by the ChildProcess object. This can happen, for instance, when the child process has already exited. 如果没有提供 callback 函数且无法发送消息, ChildProcess 对象将发出 ’error’ 事件。例如,当子进程已退出时,可能会发生这种情况。

      subprocess.send() will return false if the channel has closed or when the backlog of unsent messages exceeds a threshold that makes it unwise to send more. Otherwise, the method returns true. The callback function can be used to implement flow control. subprocess.send() 在通道已关闭或未发送消息积压量超过不适合再发送更多消息的阈值时,将返回 false 。否则,该方法将返回 true 。 callback 函数可用于实现流控制。

      Example: sending a server object 示例:发送服务器对象# The sendHandle argument can be used, for instance, to pass the handle of a TCP server object to the child process as illustrated in the example below: 例如, sendHandle 参数可用于将 TCP 服务器对象的句柄传递给子进程,如下例所示:

      const subprocess = require(’node:child_process’).fork(‘subprocess.js’);

      // Open up the server object and send the handle. const server = require(’node:net’).createServer(); server.on(‘connection’, (socket) => { socket.end(‘handled by parent’); }); server.listen(1337, () => { subprocess.send(‘server’, server); }); COPY The child would then receive the server object as: 然后,子进程将收到服务器对象,如下所示:

      process.on(‘message’, (m, server) => { if (m === ‘server’) { server.on(‘connection’, (socket) => { socket.end(‘handled by child’); }); } }); COPY Once the server is now shared between the parent and child, some connections can be handled by the parent and some by the child. 现在,父进程和子进程之间共享服务器后,某些连接 可以由父进程处理,某些连接可以由子进程处理。

      While the example above uses a server created using the node:net module, node:dgram module servers use exactly the same workflow with the exceptions of listening on a ‘message’ event instead of ‘connection’ and using server.bind() instead of server.listen(). This is, however, only supported on Unix platforms. 虽然上面的示例使用的是使用 node:net 模块创建的服务器,但 node:dgram 模块服务器使用完全相同的工作流,除了监听 ‘message’ 事件而不是 ‘connection’ 事件,以及使用 server.bind() 而不是 server.listen() 之外。但是,这仅在 Unix 平台上受支持。

      Example: sending a socket object 示例:发送套接字对象# Similarly, the sendHandler argument can be used to pass the handle of a socket to the child process. The example below spawns two children that each handle connections with “normal” or “special” priority: 同样, sendHandler 参数可用于将套接字的句柄传递给子进程。以下示例生成两个子进程,每个子进程分别处理具有“普通”或“特殊”优先级的连接:

      const { fork } = require(’node:child_process’); const normal = fork(‘subprocess.js’, [’normal’]); const special = fork(‘subprocess.js’, [‘special’]);

      // Open up the server and send sockets to child. Use pauseOnConnect to prevent // the sockets from being read before they are sent to the child process. const server = require(’node:net’).createServer({ pauseOnConnect: true }); server.on(‘connection’, (socket) => {

      // If this is special priority… if (socket.remoteAddress === ‘74.125.127.100’) { special.send(‘socket’, socket); return; } // This is normal priority. normal.send(‘socket’, socket); }); server.listen(1337); COPY The subprocess.js would receive the socket handle as the second argument passed to the event callback function: subprocess.js 会将套接字句柄作为传递给事件回调函数的第二个参数接收:

      process.on(‘message’, (m, socket) => { if (m === ‘socket’) { if (socket) { // Check that the client socket exists. // It is possible for the socket to be closed between the time it is // sent and the time it is received in the child process. socket.end(Request handled with ${process.argv[2]} priority); } } }); COPY Do not use .maxConnections on a socket that has been passed to a subprocess. The parent cannot track when the socket is destroyed. 请勿对已传递给子进程的套接字使用 .maxConnections 。父进程无法跟踪套接字何时被销毁。

      Any ‘message’ handlers in the subprocess should verify that socket exists, as the connection may have been closed during the time it takes to send the connection to the child. 子进程中的任何 ‘message’ 处理程序都应验证 socket 是否存在,因为在将连接发送到子进程期间,连接可能已关闭。

      subprocess.signalCode# | The subprocess.signalCode property indicates the signal received by the child process if any, else null. subprocess.signalCode 属性指示子进程收到的信号(如果有),否则为 null 。

      subprocess.spawnargs# The subprocess.spawnargs property represents the full list of command-line arguments the child process was launched with. subprocess.spawnargs 属性表示子进程启动时使用的命令行参数的完整列表。

      subprocess.spawnfile# The subprocess.spawnfile property indicates the executable file name of the child process that is launched. subprocess.spawnfile 属性指示启动的子进程的可执行文件名。

      For child_process.fork(), its value will be equal to process.execPath. For child_process.spawn(), its value will be the name of the executable file. For child_process.exec(), its value will be the name of the shell in which the child process is launched. 对于 child_process.fork() ,其值将等于 process.execPath 。对于 child_process.spawn() ,其值将是可执行文件的名称。对于 child_process.exec() ,其值将是启动子进程的 shell 的名称。

      subprocess.stderr# Added in: v0.1.90 添加于:v0.1.90 <stream.Readable> | | A Readable Stream that represents the child process’s stderr. 表示子进程的 stderr 的 Readable Stream 。

      If the child was spawned with stdio[2] set to anything other than ‘pipe’, then this will be null.

      subprocess.stderr is an alias for subprocess.stdio[2]. Both properties will refer to the same value. subprocess.stderr 是 subprocess.stdio[2] 的别名。这两个属性都将引用相同的值。

      The subprocess.stderr property can be null or undefined if the child process could not be successfully spawned. 如果子进程无法成功生成,则 subprocess.stderr 属性可以是 null 或 undefined 。

      subprocess.stdin# Added in: v0.1.90 <stream.Writable> | | A Writable Stream that represents the child process’s stdin.

      If a child process waits to read all of its input, the child will not continue until this stream has been closed via end().

      If the child was spawned with stdio[0] set to anything other than ‘pipe’, then this will be null.

      subprocess.stdin is an alias for subprocess.stdio[0]. Both properties will refer to the same value.

      The subprocess.stdin property can be null or undefined if the child process could not be successfully spawned.

      subprocess.stdio# Added in: v0.7.10 添加于:v0.7.10 <数组><保持此符号>一个稀疏的管道数组到子进程,对应于传递给 的 选项中的位置,该位置已设置为值 。 、 和 也分别可用作 、 和 。 是 的别名。这两个属性都将引用相同的值。<保持此符号> 属性可以是 或 ,如果子进程无法成功生成。<保持此符号>一个 表示子进程的 。<保持此符号>如果子进程等待读取其所有输入,则子进程将不会继续,直到此流通过 关闭。<保持此符号>如果子进程以 生成,并且设置为除 之外的任何内容,那么这将是 。<保持此符号>在 v0.1.90 中添加 <保持此符号> | | <保持此符号>如果子进程以 生成,并且设置为除 之外的任何内容,那么这将是 。 A sparse array of pipes to the child process, corresponding with positions in the stdio option passed to child_process.spawn() that have been set to the value ‘pipe’. subprocess.stdio[0], subprocess.stdio[1], and subprocess.stdio[2] are also available as subprocess.stdin, subprocess.stdout, and subprocess.stderr, respectively.

      In the following example, only the child’s fd 1 (stdout) is configured as a pipe, so only the parent’s subprocess.stdio[1] is a stream, all other values in the array are null. 在以下示例中,只有子代的 fd 1 (stdout)被配置为管道,因此只有父代的 subprocess.stdio[1] 是流,数组中的所有其他值都是 null 。

      const assert = require(’node:assert’); const fs = require(’node:fs’); const child_process = require(’node:child_process’);

      const subprocess = child_process.spawn(’ls’, { stdio: [ 0, // Use parent’s stdin for child. ‘pipe’, // Pipe child’s stdout to parent. fs.openSync(’err.out’, ‘w’), // Direct child’s stderr to a file. ], });

      assert.strictEqual(subprocess.stdio[0], null); assert.strictEqual(subprocess.stdio[0], subprocess.stdin);

      assert(subprocess.stdout); assert.strictEqual(subprocess.stdio[1], subprocess.stdout);

      assert.strictEqual(subprocess.stdio[2], null); assert.strictEqual(subprocess.stdio[2], subprocess.stderr); COPY The subprocess.stdio property can be undefined if the child process could not be successfully spawned. 如果无法成功生成子进程,则 subprocess.stdio 属性可以为 undefined 。

      subprocess.stdout# Added in: v0.1.90 添加于:v0.1.90 <stream.Readable> | | A Readable Stream that represents the child process’s stdout. 表示子进程的 stdout 的 Readable Stream 。

      If the child was spawned with stdio[1] set to anything other than ‘pipe’, then this will be null. 如果子进程使用除 ‘pipe’ 之外的任何值生成 stdio[1] ,则这将为 null 。

      subprocess.stdout is an alias for subprocess.stdio[1]. Both properties will refer to the same value. subprocess.stdout 是 subprocess.stdio[1] 的别名。两个属性都将引用相同的值。

      const { spawn } = require(’node:child_process’);

      const subprocess = spawn(’ls’);

      subprocess.stdout.on(‘data’, (data) => { console.log(Received chunk ${data}); }); COPY The subprocess.stdout property can be null or undefined if the child process could not be successfully spawned. 如果无法成功生成子进程,则 subprocess.stdout 属性可以为 null 或 undefined 。

      subprocess.unref()# Added in: v0.7.10 添加于:v0.7.10 By default, the parent will wait for the detached child to exit. To prevent the parent from waiting for a given subprocess to exit, use the subprocess.unref() method. Doing so will cause the parent’s event loop to not include the child in its reference count, allowing the parent to exit independently of the child, unless there is an established IPC channel between the child and the parent. 默认情况下,父进程将等待分离的子进程退出。若要阻止父进程等待给定的 subprocess 退出,请使用 subprocess.unref() 方法。这样做会导致父进程的事件循环不将子进程包含在其引用计数中,从而允许父进程独立于子进程退出,除非子进程与父进程之间建立了 IPC 通道。

      const { spawn } = require(’node:child_process’);

      const subprocess = spawn(process.argv[0], [‘child_program.js’], { detached: true, stdio: ‘ignore’, });

      subprocess.unref(); COPY maxBuffer and Unicode maxBuffer 和 Unicode# The maxBuffer option specifies the largest number of bytes allowed on stdout or stderr. If this value is exceeded, then the child process is terminated. This impacts output that includes multibyte character encodings such as UTF-8 or UTF-16. For instance, console.log(‘中文测试’) will send 13 UTF-8 encoded bytes to stdout although there are only 4 characters. maxBuffer 选项指定 stdout 或 stderr 上允许的最大字节数。如果超过此值,则子进程将终止。这会影响包含多字节字符编码(如 UTF-8 或 UTF-16)的输出。例如, console.log(‘中文测试’) 将向 stdout 发送 13 个 UTF-8 编码的字节,尽管只有 4 个字符。

      Shell requirements Shell 要求# The shell should understand the -c switch. If the shell is ‘cmd.exe’, it should understand the /d /s /c switches and command-line parsing should be compatible. Shell 应理解 -c 开关。如果 Shell 是 ‘cmd.exe’ ,它应理解 /d /s /c 开关,并且命令行解析应兼容。

      Default Windows shell 默认 Windows Shell# Although Microsoft specifies %COMSPEC% must contain the path to ‘cmd.exe’ in the root environment, child processes are not always subject to the same requirement. Thus, in child_process functions where a shell can be spawned, ‘cmd.exe’ is used as a fallback if process.env.ComSpec is unavailable. 尽管 Microsoft 指定 %COMSPEC% 必须包含根环境中 ‘cmd.exe’ 的路径,但子进程并不总是受制于相同的要求。因此,在 child_process 函数中,如果 process.env.ComSpec 不可用的情况下,可以使用 ‘cmd.exe’ 作为后备。

      Advanced serialization 高级序列化# Added in: v13.2.0, v12.16.0 添加于:v13.2.0、v12.16.0 Child processes support a serialization mechanism for IPC that is based on the serialization API of the node:v8 module, based on the HTML structured clone algorithm. This is generally more powerful and supports more built-in JavaScript object types, such as BigInt, Map and Set, ArrayBuffer and TypedArray, Buffer, Error, RegExp etc. 子进程支持一种基于 node:v8 模块序列化 API 的 IPC 序列化机制,该机制基于 HTML 结构化克隆算法。这通常功能更强大,并支持更多内置 JavaScript 对象类型,例如 BigInt 、 Map 和 Set 、 ArrayBuffer 和 TypedArray 、 Buffer 、 Error 、 RegExp 等。

      However, this format is not a full superset of JSON, and e.g. properties set on objects of such built-in types will not be passed on through the serialization step. Additionally, performance may not be equivalent to that of JSON, depending on the structure of the passed data. Therefore, this feature requires opting in by setting the serialization option to ‘advanced’ when calling child_process.spawn() or child_process.fork(). 但是,此格式不是 JSON 的完整超集,例如,在此类内置类型的对象上设置的属性将不会通过序列化步骤传递。此外,性能可能不等于 JSON 的性能,具体取决于所传递数据的结构。因此,此功能需要在调用 child_process.spawn() 或 child_process.fork() 时通过将 serialization 选项设置为 ‘advanced’ 来选择加入。

      上一页