feat: add http cache support to requests from utility process Add `session` and `partition` options to `utilityProcess.fork()` to allow utility processes to use a session-specific network context instead of the system network context. This enables HTTP caching, cookie isolation, and webRequest interception for utility process network requests. When `respondToAuthRequestsFromMainProcess` is true and a session is provided, HTTP 401/407 auth challenges now emit a `login` event on the UtilityProcess instance rather than on `app`. Without a session, auth challenges continue to emit on `app` for backward compatibility.
9.5 KiB
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
Methods
utilityProcess.fork(modulePath[, args][, options])
modulePathstring - Path to the script that should run as entrypoint in the child process.argsstring[] (optional) - List of string arguments that will be available asprocess.argvin the child process.optionsObject (optional)envObject (optional) - Environment key-value pairs. Default isprocess.env.execArgvstring[] (optional) - List of string arguments passed to the executable.cwdstring (optional) - Current working directory of the child process.sessionSession (optional) - Sets the session used by the process for network requests. By default, network requests from the utility process will use the system network context which does not have HTTP cache support. Setting a session enables HTTP caching and other session-specific network features. See session for more information.partitionstring (optional) - Sets the session used by the process according to the session's partition string. Ifpartitionstarts withpersist:, the process will use a persistent session available to all pages in the app with the samepartition. If there is nopersist:prefix, the process will use an in-memory session. By assigning the samepartition, multiple processes can share the same session. If thesessionoption is set, this option is ignored.stdio(string[] | string) (optional) - Allows configuring the mode forstdoutandstderrof the child process. Default isinherit. String value can be one ofpipe,ignore,inherit, for more details on these values you can refer to stdio documentation from Node.js. Currently this option only supports configuringstdoutandstderrto eitherpipe,inheritorignore. Configuringstdinto any property other thanignoreis not supported and will result in an error. For example, the supported values will be processed as following:pipe: equivalent to ['ignore', 'pipe', 'pipe']ignore: equivalent to ['ignore', 'ignore', 'ignore']inherit: equivalent to ['ignore', 'inherit', 'inherit'] (the default)
serviceNamestring (optional) - Name of the process that will appear innameproperty ofProcessMetricreturned byapp.getAppMetricsandchild-process-goneevent ofapp. Default isNode Utility Process.allowLoadingUnsignedLibrariesboolean (optional) macOS - With this flag, the utility process will be launched via theElectron Helper (Plugin).apphelper executable on macOS, which can be codesigned withcom.apple.security.cs.disable-library-validationandcom.apple.security.cs.allow-unsigned-executable-memoryentitlements. This will allow the utility process to load unsigned libraries. Unless you specifically need this capability, it is best to leave this disabled. Default isfalse.disclaimboolean (optional) macOS - With this flag, the utility process will disclaim responsibility for the child process. This causes the operating system to consider the child process as a separate entity for purposes of security policies like Transparency, Consent, and Control (TCC). When responsibility is disclaimed, the parent process will not be attributed for any TCC requests initiated by the child process. This is useful when launching processes that run third-party or otherwise untrusted code. Default isfalse.respondToAuthRequestsFromMainProcessboolean (optional) - With this flag, all HTTP 401 and 407 network requests created via the net module will allow responding to them via theloginevent on theUtilityProcessinstance when asessionis provided, or via theapp#loginevent in the main process when using the default system network context. Without this flag, auth challenges are handled by the defaultloginevent on theClientRequestobject. Default isfalse.
Returns UtilityProcess
Note
utilityProcess.forkcan only be called after thereadyevent has been emitted onApp.
Class: UtilityProcess
Instances of the
UtilityProcessrepresent the Chromium spawned child process with Node.js integration.
UtilityProcess is an EventEmitter.
Instance Methods
child.postMessage(message, [transfer])
messageanytransferMessagePortMain[] (optional)
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()
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
the child process exits, then the value is undefined after the exit event is emitted.
const child = utilityProcess.fork(path.join(__dirname, 'test.js'))
console.log(child.pid) // undefined
child.on('spawn', () => {
console.log(child.pid) // Integer
})
child.on('exit', () => {
console.log(child.pid) // undefined
})
Note
You can use the
pidto determine if the process is currently running.
child.stdout
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
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
Event: 'spawn'
Emitted once the child process has spawned successfully.
Event: 'error' Experimental
Returns:
typestring - Type of error. One of the following values:FatalError
locationstring - Source location from where the error originated.reportstring -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.
Event: 'exit'
Returns:
codenumber - Contains the exit code for the process obtained from waitpid on POSIX, or GetExitCodeProcess on Windows.
Emitted after the child process ends.
Event: 'message'
Returns:
messageany
Emitted when the child process sends a message using process.parentPort.postMessage().
Event: 'login'
Returns:
authenticationResponseDetailsObjecturlURLpidnumber
authInfoObjectisProxybooleanschemestringhoststringportIntegerrealmstring
callbackFunctionusernamestring (optional)passwordstring (optional)
Emitted when the utility process encounters an HTTP 401 or 407 authentication challenge, if the
process was created with both respondToAuthRequestsFromMainProcess: true and a session option.
The callback should be called with credentials to respond to the challenge. Calling callback
without arguments will cancel the request.
This behaves the same as the login event on app but is scoped to the
individual utility process instance.
const { session, utilityProcess } = require('electron')
const ses = session.defaultSession
const child = utilityProcess.fork('./worker.js', [], {
session: ses,
respondToAuthRequestsFromMainProcess: true
})
child.on('login', (authenticationResponseDetails, authInfo, callback) => {
callback('username', 'password')
})