メインコンテンツへ飛ぶ

utilityProcess

utilityProcess は、Node.js と Message ポートが有効な子プロセスを作成します。 Node.js の child_process.fork API 相当の機能を提供しますが、代わりに Chromium の Services API で子プロセスを起動します。

プロセス: メイン

メソッド

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

  • modulePath string - 子プロセスのエントリポイントとして起動されるスクリプトへのパスです。
  • args string[] (任意) - その子プロセスで process.argv として利用可能な引数の文字列リストです。
  • options Object (任意)
    • env Object (任意) - 環境変数のキーバリューペアです。 デフォルトはprocess.envです。
    • execArgv string[] (任意) - 実行形式に渡される引数の文字列リストです。
    • cwd string (任意) - 子プロセスのカレントワーキングディレクトリです。
    • 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[] | string) (任意) - その子プロセスの stdoutstderr のモードを設定できます。 デフォルトはinheritです。 文字列の値は pipeignoreinherit のうちの 1 つにできます。これらの値について詳しくは Node.js の stdio ドキュメントをご参照ください。 現在このオプションは stdoutstderrpipeinherit または ignore のいずれかに設定することのみをサポートしています。 stdinignore 以外のプロパティに設定することはサポートされておらず、エラーが発生します。 例えば、サポートされている値は以下のように処理されます。
      • pipe: ['ignore', 'pipe', 'pipe'] と等価です
      • ignore: ['ignore', 'ignore', 'ignore'] と等価です
      • inherit: ['ignore', 'inherit', 'inherit'] と等価です (既定)
    • serviceName string (任意) - プロセス名で、app.getAppMetrics 及び appchild-process-gone イベント で返される ProcessMetricname プロパティに現れます。 デフォルトはNode Utility Processです。
    • allowLoadingUnsignedLibraries boolean (任意) macOS - このフラグを使用すると、ユーティリティプロセスは macOS の Electron Helper (Plugin).app ヘルパー実行形式を介して起動され、これは com.apple.security.cs.disable-library-validationcom.apple.security.cs.allow-unsigned-executable-memory の エンタイトルメントでコード署名できます。 これにより、ユーティリティプロセスが未署名のライブラリをロードできるようになります。 特にこの機能を必要としなければ、無効にしておくことを推奨します。 省略値は 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. 省略値は 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. 省略値は false です。

戻り値 UtilityProcess

note

utilityProcess.fork は、appready イベントが発生した後にのみ呼び出すことができます。

クラス: UtilityProcess

UtilityProcess のインスタンスは、Node.js を統合した Chromium が生成した子プロセスを表します。

UtilityProcessEventEmitter を継承しています。

インスタンスメソッド

child.postMessage(message, [transfer])

  • message any
  • transfer MessagePortMain[] (任意)

メッセージをその子プロセスに送信し、任意でゼロ個以上の MessagePortMain オブジェクトの所有権を転送します。

以下がその例です。

// メインプロセス
const { port1, port2 } = new MessageChannelMain()
const child = utilityProcess.fork(path.join(__dirname, 'test.js'))
child.postMessage({ message: 'hello' }, [port1])

// 子プロセス
process.parentPort.once('message', (e) => {
const [port] = e.ports
// ...
})

child.kill()

戻り値 boolean

プロセスを正常終了させます。 POSIX では SIGTERM を使用しますが、アプリ終了時にはプロセスを刈り取ります。 この関数は kill が成功した場合に true を、そうでない場合に false を返します。

インスタンスプロパティ

child.pid

Integer | undefined 型で、その子プロセスのプロセス識別子 (PID) を表します。 子プロセスが正常に生成されるまで、その値は undefined になります。 子プロセスが終了すると、exit イベントが発生し、以降この値は undefined になります。

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

pid を使用して、プロセスが現在実行中かどうかを判定できます。

child.stdout

NodeJS.ReadableStream | null 型で、その子プロセスの標準出力を表します。 options.stdio[1] を 'pipe' 以外に設定して子プロセスを生成した場合、これは null になります。 子プロセスが終了すると、exit イベントが発生し、以降この値は null になります。

// メインプロセス
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

NodeJS.ReadableStream | null 型で、その子プロセスの標準エラー出力を表します。 options.stdio[2] を 'pipe' 以外に設定して子プロセスを生成した場合、これは null になります。 子プロセスが終了すると、exit イベントが発生し、以降この値は null になります。

インスタンスイベント

イベント: 'spawn'

その子プロセスが正常に生成されると発生します。

イベント: 'error' 実験的

戻り値:

  • type string - エラーの種別。 以下の値のいずれかです。
    • FatalError
  • location string - エラーが発生したソースの位置。
  • report string - Node.js 診断レポート

V8 からの継続不可能なエラーにより子プロセスを終了する必要がある場合に発生します。

error イベントのリッスンに関係なく、子プロセスが終了し、exit イベントが発生します。

イベント: 'exit'

戻り値:

  • code number - プロセスの終了コードを格納しており、POSIX では waitpid、Windows では GetExitCodeProcess から得られるものです。

その子プロセスが終了した後に発生します。

イベント: 'message'

戻り値:

  • message any

その子プロセスが process.parentPort.postMessage() でメッセージを送信したときに発生します。

イベント: 'login'

戻り値:

  • authenticationResponseDetails Object
    • url URL
    • pid number
  • authInfo Object
    • isProxy boolean
    • scheme string
    • host string
    • port Integer
    • realm string
  • callback Function
    • username string (任意)
    • password string (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')
})