Skip to main content

utilityProcess

utilityProcess 创建一个启用 Node.js 和消息端口的子进程。它提供了与 Node.js 中的 child_process.fork API 等效的功能,但使用 Chromium 中的 服务 API 来启动子进程。

¥utilityProcess creates a child process with Node.js and Message ports enabled. It provides the equivalent of child_process.fork API from Node.js but instead uses Services API from Chromium to launch the child process.

进程:主进程

¥Process: Main

方法

¥Methods

utilityProcess.fork(modulePath[, args][, options])

  • modulePath 字符串 - 应作为子进程中的入口点运行的脚本的路径。

    ¥modulePath string - Path to the script that should run as entrypoint in the child process.

  • args 字符串[](可选) - 将在子进程中用作 process.argv 的字符串参数列表。

    ¥args string[] (optional) - List of string arguments that will be available as process.argv in the child process.

  • options 对象(可选)

    ¥options Object (optional)

    • env 对象(可选) - 环境键值对。默认为 process.env

      ¥env Object (optional) - Environment key-value pairs. Default is process.env.

    • execArgv 字符串[](可选) - 传递给可执行文件的字符串参数列表。

      ¥execArgv string[] (optional) - List of string arguments passed to the executable.

    • cwd 字符串(可选) - 子进程的当前工作目录。

      ¥cwd string (optional) - Current working directory of the child process.

    • stdio(字符串[] |字符串)(可选) - 允许配置子进程的 stdoutstderr 模式。默认为 inherit。字符串值可以是 pipeignoreinherit 之一,有关这些值的更多详细信息,你可以参考 Node.js 的 stdio 文档。目前该选项仅支持将 stdoutstderr 配置为 pipeinheritignore。不支持将 stdin 配置为 ignore 以外的任何属性,并将导致错误。例如,支持的值将按如下方式处理:

      ¥stdio (string[] | string) (optional) - Allows configuring the mode for stdout and stderr of the child process. Default is inherit. String value can be one of pipe, ignore, inherit, for more details on these values you can refer to stdio documentation from Node.js. Currently this option only supports configuring stdout and stderr to either pipe, inherit or ignore. Configuring stdin to any property other than ignore is not supported and will result in an error. For example, the supported values will be processed as following:

      • pipe:相当于 ['ignore','pipe','pipe']

        ¥pipe: equivalent to ['ignore', 'pipe', 'pipe']

      • ignore:相当于 ['ignore','ignore','ignore']

        ¥ignore: equivalent to ['ignore', 'ignore', 'ignore']

      • inherit:相当于 ['ignore', 'inherit', 'inherit'](默认)

        ¥inherit: equivalent to ['ignore', 'inherit', 'inherit'] (the default)

    • serviceName 字符串(可选) - 将出现在 app.getAppMetricsappchild-process-gone 事件 返回的 ProcessMetricname 属性中的进程名称。默认为 Node Utility Process

      ¥serviceName string (optional) - Name of the process that will appear in name property of ProcessMetric returned by app.getAppMetrics and child-process-gone event of app. Default is Node Utility Process.

    • allowLoadingUnsignedLibraries 布尔值(可选)macOS - 使用此标志,实用程序进程将通过 macOS 上的 Electron Helper (Plugin).app 辅助程序可执行文件启动,该可执行文件可以使用 com.apple.security.cs.disable-library-validationcom.apple.security.cs.allow-unsigned-executable-memory 权利进行联合签名。这将允许实用程序进程加载未签名的库。除非你特别需要此功能,否则最好禁用此功能。默认为 false

      ¥allowLoadingUnsignedLibraries boolean (optional) macOS - With this flag, the utility process will be launched via the Electron Helper (Plugin).app helper executable on macOS, which can be codesigned with com.apple.security.cs.disable-library-validation and com.apple.security.cs.allow-unsigned-executable-memory entitlements. This will allow the utility process to load unsigned libraries. Unless you specifically need this capability, it is best to leave this disabled. Default is false.

    • respondToAuthRequestsFromMainProcess 布尔值(可选) - 使用此标志,通过 net 模块 创建的所有 HTTP 401 和 407 网络请求都将允许通过主进程中的 app#login 事件而不是 ClientRequest 对象上的默认 login 事件对它们进行响应。

      ¥respondToAuthRequestsFromMainProcess boolean (optional) - With this flag, all HTTP 401 and 407 network requests created via the net module will allow responding to them via the app#login event in the main process instead of the default login event on the ClientRequest object.

返回 UtilityProcess

¥Returns UtilityProcess

类:UtilityProcess

¥Class: UtilityProcess

UtilityProcess 的实例代表 Chromium 通过 Node.js 集成生成的子进程。

¥Instances of the UtilityProcess represent the Chromium spawned child process with Node.js integration.

UtilityProcessEventEmitter

¥UtilityProcess is an EventEmitter.

实例方法

¥Instance Methods

child.postMessage(message, [transfer])

  • message 任意

    ¥message any

  • transfer MessagePortMain[](可选)

    ¥transfer MessagePortMain[] (optional)

向子进程发送消息,可选择转让零个或多个 MessagePortMain 对象的所有权。

¥Send a message to the child process, optionally transferring ownership of zero or more MessagePortMain objects.

例如:

¥For example:

// Main process
const { port1, port2 } = new MessageChannelMain()
const child = utilityProcess.fork(path.join(__dirname, 'test.js'))
child.postMessage({ message: 'hello' }, [port1])

// Child process
process.parentPort.once('message', (e) => {
const [port] = e.ports
// ...
})

child.kill()

返回 boolean

¥Returns boolean

优雅地终止进程。在 POSIX 上,它使用 SIGTERM 但会确保进程在退出时被收获。如果杀死成功,该函数返回 true,否则返回 false。

¥Terminates the process gracefully. On POSIX, it uses SIGTERM but will ensure the process is reaped on exit. This function returns true if the kill is successful, and false otherwise.

实例属性

¥Instance Properties

child.pid

Integer | undefined 代表子进程的进程标识符 (PID)。如果子进程由于错误而未能生成,则该值为 undefined。当子进程退出时,发出 exit 事件后该值为 undefined

¥A Integer | undefined representing the process identifier (PID) of the child process. If the child process fails to spawn due to errors, then the value is undefined. When the child process exits, then the value is undefined after the exit event is emitted.

child.stdout

代表子进程的标准输出的 NodeJS.ReadableStream | null。如果子进程是在 options.stdio[1] 设置为 'pipe' 以外的任何值的情况下生成的,那么这将是 null。当子进程退出时,发出 exit 事件后该值为 null

¥A NodeJS.ReadableStream | null that represents the child process's stdout. If the child was spawned with options.stdio[1] set to anything other than 'pipe', then this will be null. When the child process exits, then the value is null after the exit event is emitted.

// Main process
const { port1, port2 } = new MessageChannelMain()
const child = utilityProcess.fork(path.join(__dirname, 'test.js'))
child.stdout.on('data', (data) => {
console.log(`Received chunk ${data}`)
})

child.stderr

代表子进程的 stderr 的 NodeJS.ReadableStream | null。如果子进程是在 options.stdio[2] 设置为 'pipe' 以外的任何值的情况下生成的,那么这将是 null。当子进程退出时,发出 exit 事件后该值为 null

¥A NodeJS.ReadableStream | null that represents the child process's stderr. If the child was spawned with options.stdio[2] set to anything other than 'pipe', then this will be null. When the child process exits, then the value is null after the exit event is emitted.

实例事件

¥Instance Events

事件:'spawn'

¥Event: 'spawn'

子进程成功生成后发出。

¥Emitted once the child process has spawned successfully.

事件:'exit'

¥Event: 'exit'

返回:

¥Returns:

  • code 数字 - 包含从 posix 上的 waitpid 或 Windows 上的 GetExitCodeProcess 获取的进程的退出代码。

    ¥code number - Contains the exit code for the process obtained from waitpid on posix, or GetExitCodeProcess on windows.

子进程结束后发出。

¥Emitted after the child process ends.

事件:'message'

¥Event: 'message'

返回:

¥Returns:

  • message 任意

    ¥message any

当子进程使用 process.parentPort.postMessage() 发送消息时发出。

¥Emitted when the child process sends a message using process.parentPort.postMessage().