electronjs.org-new/docs/latest/api/utility-process.md

179 строки
7.1 KiB
Markdown
Исходник Постоянная ссылка Обычный вид История

2022-11-30 09:06:42 +03:00
---
title: "utilityProcess"
description: "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."
slug: utility-process
hide_title: false
---
# utilityProcess
`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](latest/glossary.md#main-process)<br />
## Methods
### `utilityProcess.fork(modulePath[, args][, options])`
* `modulePath` string - Path to the script that should run as entrypoint in the child process.
* `args` string[] (optional) - List of string arguments that will be available as `process.argv`
in the child process.
* `options` Object (optional)
* `env` Object (optional) - Environment key-value pairs. Default is `process.env`.
* `execArgv` string[] (optional) - List of string arguments passed to the executable.
* `cwd` string (optional) - Current working directory of the child process.
* `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
2024-02-22 01:18:41 +03:00
`stderr` to either `pipe`, `inherit` or `ignore`. Configuring `stdin` to any property other than `ignore` is not supported and will result in an error.
2022-11-30 09:06:42 +03:00
For example, the supported values will be processed as following:
2024-02-22 01:18:41 +03:00
* `pipe`: equivalent to \['ignore', 'pipe', 'pipe']
2023-04-05 18:09:54 +03:00
* `ignore`: equivalent to \['ignore', 'ignore', 'ignore']
2024-02-22 01:18:41 +03:00
* `inherit`: equivalent to \['ignore', 'inherit', 'inherit'] (the default)
2022-11-30 09:06:42 +03:00
* `serviceName` string (optional) - Name of the process that will appear in `name` property of
2023-12-05 11:58:34 +03:00
[`ProcessMetric`](latest/api/structures/process-metric.md) returned by [`app.getAppMetrics`](latest/api/app.md#appgetappmetrics)
and [`child-process-gone` event of `app`](latest/api/app.md#event-child-process-gone).
2023-10-24 18:16:36 +03:00
Default is `Node Utility Process`.
2022-11-30 09:06:42 +03:00
* `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`.
2024-08-20 21:26:49 +03:00
* `respondToAuthRequestsFromMainProcess` boolean (optional) - With this flag, all HTTP 401 and 407 network
requests created via the [net module](latest/api/net.md) will allow responding to them via the [`app#login`](latest/api/app.md#event-login) event in the main process instead of the default [`login`](latest/api/client-request.md#event-login) event on the [`ClientRequest`](latest/api/client-request.md) object.
2022-11-30 09:06:42 +03:00
Returns [`UtilityProcess`](latest/api/utility-process.md#class-utilityprocess)
## Class: UtilityProcess
> Instances of the `UtilityProcess` represent the Chromium spawned child process
> with Node.js integration.
`UtilityProcess` is an [EventEmitter][event-emitter].
### Instance Methods
#### `child.postMessage(message, [transfer])`
* `message` any
* `transfer` MessagePortMain[] (optional)
Send a message to the child process, optionally transferring ownership of
zero or more [`MessagePortMain`][] objects.
For example:
```js
// 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()`
Returns `boolean`
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`
A `Integer | undefined` representing the process identifier (PID) of the child process.
Until the child process has spawned successfully, the value is `undefined`. When
2022-11-30 09:06:42 +03:00
the child process exits, then the value is `undefined` after the `exit` event is emitted.
```js
const child = utilityProcess.fork(path.join(__dirname, 'test.js'))
2024-11-19 02:02:41 +03:00
console.log(child.pid) // undefined
child.on('spawn', () => {
console.log(child.pid) // Integer
})
child.on('exit', () => {
console.log(child.pid) // undefined
})
```
2024-11-19 02:02:41 +03:00
**Note:** You can use the `pid` to determine if the process is currently running.
2022-11-30 09:06:42 +03:00
#### `child.stdout`
A `NodeJS.ReadableStream | null` that represents the child process's stdout.
2023-04-05 18:09:54 +03:00
If the child was spawned with options.stdio\[1] set to anything other than 'pipe', then this will be `null`.
2022-11-30 09:06:42 +03:00
When the child process exits, then the value is `null` after the `exit` event is emitted.
```js
// 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`
A `NodeJS.ReadableStream | null` that represents the child process's stderr.
2023-04-05 18:09:54 +03:00
If the child was spawned with options.stdio\[2] set to anything other than 'pipe', then this will be `null`.
2022-11-30 09:06:42 +03:00
When the child process exits, then the value is `null` after the `exit` event is emitted.
### Instance Events
#### Event: 'spawn'
Emitted once the child process has spawned successfully.
#### Event: 'error' _Experimental_
Returns:
* `type` string - Type of error. One of the following values:
* `FatalError`
* `location` string - Source location from where the error originated.
* `report` string - [`Node.js diagnostic report`][].
Emitted when the child process needs to terminate due to non continuable error from V8.
No matter if you listen to the `error` event, the `exit` event will be emitted after the
child process terminates.
2022-11-30 09:06:42 +03:00
#### Event: 'exit'
Returns:
* `code` number - Contains the exit code for
the process obtained from waitpid on POSIX, or GetExitCodeProcess on Windows.
2022-11-30 09:06:42 +03:00
Emitted after the child process ends.
#### Event: 'message'
Returns:
* `message` any
Emitted when the child process sends a message using [`process.parentPort.postMessage()`](latest/api/process.md#processparentport).
[`child_process.fork`]: https://nodejs.org/dist/latest-v16.x/docs/api/child_process.html#child_processforkmodulepath-args-options
2023-01-10 03:35:11 +03:00
[Services API]: https://chromium.googlesource.com/chromium/src/+/main/docs/mojo_and_services.md
2022-11-30 09:06:42 +03:00
[stdio]: https://nodejs.org/dist/latest/docs/api/child_process.html#optionsstdio
[event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter
2022-12-15 01:41:05 +03:00
[`MessagePortMain`]: latest/api/message-port-main.md
[`Node.js diagnostic report`]: https://nodejs.org/docs/latest/api/report.html#diagnostic-report