Saltar al contenido principal

utilityProcess

utilityProcess crea un proceso hijo con los puertos de Node.js y Message habilitados. Este proporciona un equivalente al API child_process.fork de Node.js, pero en su lugar usa el API Services de Chromium para lanzar el proceso hijo.

Proceso: principal

Métodos

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

  • Cadena modulePath - Ruta al script que debe ejecutarse como punto de entrada del proceso hijo.
  • args string[] (opcional) - Listado de argumentos de cadena que deben estar disponibles como process.argv en el proceso hijo.
  • options Object (opcional)
    • Objeto env (opcional) - Pares de clave-valor del entorno. Por defecto es process.env.
    • execArgv string[] (opcional) - Lista de cadenas de argumento enviada al ejecutable.
    • Cadena cwd (opcional) - Directorio actualmente operativo del proceso hijo.
    • session Session (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.
    • partition string (optional) - Sets the session used by the process according to the session's partition string. If partition starts with persist:, the process will use a persistent session available to all pages in the app with the same partition. If there is no persist: prefix, the process will use an in-memory session. By assigning the same partition, multiple processes can share the same session. If the session option is set, this option is ignored.
    • stdio (string[] | cadena) (opcional) - Permite configurar el modo para stdout y stderr del proceso hijo. Por defecto es inherit. El valor de la cadena puede ser uno de pipe, ignore, inherit, para más detalles sobre estos valores puede consultar la documentación stdio de Node.js. Actualmente, esta opción sólo soporta configurar stdout y stderr para pipe, inherit o ignore. Configuring stdin to any property other than ignore is not supported and will result in an error. Por ejemplo, los valores soportados se procesarán como:
      • pipe: equivalent to ['ignore', 'pipe', 'pipe']
      • ignore: equivalente a ['ignore', 'ignore', 'ignore']
      • inherit: equivalent to ['ignore', 'inherit', 'inherit'] (the default)
    • 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. Por defecto es Node Utility Process.
    • Booleano allowLoadingUnsignedLibraries (opcional) macOS - Con esta bandera, el proceso de utilidad se iniciará por medio del ejecutable de ayuda Electron Helper (Plugin).app en macOS, que puede ser codiseñado con com.apple.security.cs.disable-library-validation y los derechos adicionales de com.apple.security.cs.allow-unsigned-executable-memory. Esto le permitirá al proceso de utilidar cargar librerías sin firmar. A menos que usted necesite específicamente esta característica, es mejor dejar esto desactivado. Por defecto es false.
    • disclaim boolean (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. Por defecto es false.
    • 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 login event on the UtilityProcess instance when a session is provided, or via the app#login event in the main process when using the default system network context. Without this flag, auth challenges are handled by the default login event on the ClientRequest object. Por defecto es false.

Returns UtilityProcess

note

utilityProcess.fork can only be called after the ready event has been emitted on App.

Clase: UtilityProcess

Las instancias de UtilityProcess representan el proceso hijo generado por Chromium con la integración de Node.js.

UtilityProcess is an EventEmitter.

Métodos de Instancia

child.postMessage(message, [transfer])

  • mensaje cualquiera
  • transfer MessagePortMain[] (optional)

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

Por ejemplo:

// 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()

Devuelve boolean

Finaliza el proceso con gracia. 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.

Propiedades de la instancia

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 pid to 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.

Eventos de Instancia

Event: 'spawn'

Emitted once the child process has spawned successfully.

Event: 'error' Experimental

Devuelve:

  • type string - Type of error. Uno de los siguiente valores:
    • 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.

Event: 'exit'

Devuelve:

  • code number - Contains the exit code for the process obtained from waitpid on POSIX, or GetExitCodeProcess on Windows.

Emitted after the child process ends.

Evento: 'message'

Devuelve:

  • mensaje cualquiera

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

Evento:'login'

Devuelve:

  • authenticationResponseDetails Object
    • url URL
    • Número pid
    • isRequestForNavigation boolean - Indicates whether the request is for a navigation.
    • firstAuthAttempt boolean - Indicates whether this is the first authentication attempt.
    • responseHeaders Record<string, string | string[]> (optional) - The headers returned in the response.
  • authInfo Object
    • Booleano isProxy
    • Cadena scheme
    • Cadena host
    • puerto Íntegro
    • Cadena realm
  • callback Function
    • Cadena username (opcional)
    • Cadena password (opcional)

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')
})