child_process.fork(modulePath[, args][, options])
modulePath<string> | <URL> 子进程中要运行的模块。args<string[]> 字符串参数列表。options<Object>cwd<string> | <URL> 子进程的当前工作目录。detached<boolean> 准备子进程独立于其父进程运行。具体行为取决于平台(参见options.detached)。env<Object> 环境键值对。默认值:process.env。execPath<string> 用于创建子进程的可执行文件。execArgv<string[]> 传递给可执行文件的字符串参数列表。 默认值:process.execArgv。gid<number> 设置进程的组标识(参见setgid(2))。serialization<string> 指定用于在进程之间发送消息的序列化类型。可能的值为'json'和'advanced'。更多详情请参见 高级序列化。默认值:'json'。signal<AbortSignal> 允许使用 AbortSignal 关闭子进程。killSignal<string> | <integer> 当被生成的进程因超时或中止信号而被终止时使用的信号值。默认值:'SIGTERM'。silent<boolean> 如果为true,子进程的 stdin、stdout 和 stderr 将会被传输到父进程,否则将会继承自父进程,更多细节请参阅child_process.spawn()的stdio中的'pipe'和'inherit'选项。默认值:false。stdio<Array> | <string> 参见child_process.spawn()的stdio。当提供此选项时,它会覆盖silent。如果使用数组变体,数组中必须恰好包含一个值为'ipc'的项,否则将抛出错误。例如[0, 1, 2, 'ipc']。uid<number> 设置进程的用户身份(参见setuid(2))。windowsVerbatimArguments<boolean> 在 Windows 上不会对参数进行引号或转义。在 Unix 上会被忽略。默认值:false。timeout<number> 进程允许运行的最长时间(毫秒)。默认值:undefined。
- 返回:<ChildProcess>
child_process.fork() 方法是 child_process.spawn() 的一种特殊情况,专门用于生成新的 Node.js 进程。像 child_process.spawn() 一样,会返回一个 ChildProcess 对象。返回的 ChildProcess 将内置一个额外的通信通道,允许父进程和子进程之间互相传递消息。详情请参见 subprocess.send()。
【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.】
请记住,生成的 Node.js 子进程是独立于父进程的,唯一的例外是两者之间建立的 IPC 通信通道。每个进程都有自己的内存和 V8 实例。由于需要额外的资源分配,因此不建议生成大量的 Node.js 子进程。
【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.】
默认情况下,child_process.fork() 会使用父进程的 process.execPath 来生成新的 Node.js 实例。options 对象中的 execPath 属性允许使用替代的执行路径。
【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.】
使用自定义 execPath 启动的 Node.js 进程将通过子进程上的环境变量 NODE_CHANNEL_FD 指定的文件描述符 (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.】
与 fork(2) POSIX 系统调用不同,child_process.fork() 不会克隆当前进程。
【Unlike the fork(2) POSIX system call, child_process.fork() does not clone the
current process.】
child_process.spawn() 中可用的 shell 选项不被 child_process.fork() 支持,如果设置将被忽略。
【The shell option available in child_process.spawn() is not supported by
child_process.fork() and will be ignored if set.】
如果启用了 signal 选项,那么对相应的 AbortController 调用 .abort() 类似于对子进程调用 .kill(),只是传递给回调的错误将是 AbortError:
【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 { fork } = require('node:child_process');
const process = require('node:process');
if (process.argv[2] === 'child') {
setTimeout(() => {
console.log(`Hello from ${process.argv[2]}!`);
}, 1_000);
} else {
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
}import { fork } from 'node:child_process';
import process from 'node:process';
if (process.argv[2] === 'child') {
setTimeout(() => {
console.log(`Hello from ${process.argv[2]}!`);
}, 1_000);
} else {
const controller = new AbortController();
const { signal } = controller;
const child = fork(import.meta.url, ['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
}