utilityProcess
utilityProcess は、Node.js と Message ポートが有効な子プロセスを作成します。 Node.js の child_process.fork API 相当の機能を提供しますが、代わりに Chromium の Services API で子プロセスを起動します。
Process: Main
メソッド
utilityProcess.fork(modulePath[, args][, options])
modulePathstring - 子プロセスのエントリポイントとして起動されるスクリプトへのパスです。argsstring[] (任意) - その子プロセスでprocess.argvとして利用可能な引数の文字列リストです。
Returns UtilityProcess
Note: utilityProcess.fork can only be called after the ready event has been emitted on App.
クラス: UtilityProcess
UtilityProcessのインスタンスは、Node.js を統合した Chromium が生成した子プロセスを表します。
UtilityProcess は EventEmitter を継承しています。
インスタンスメソッド
child.postMessage(message, [transfer])
messageanytransferMessagePortMain[] (任意)
Send a message to the child process, optionally transferring ownership of zero or more MessagePortMain objects.
以下がその例です。
// メインプロセス
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) を表します。 Until the child process has spawned successfully, the value is 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: You can use the pid to determine if the process is currently running.
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'
その子プロセスが正常に生成されると発生します。
Event: 'error' Experimental
戻り値:
typestring - Type of error. 以下の値のいずれかです。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.
イベント: 'exit'
戻り値:
codenumber - Contains the exit code for the process obtained from waitpid on POSIX, or GetExitCodeProcess on Windows.
その子プロセスが終了した後に発生します。
イベント: 'message'
戻り値:
messageany
Emitted when the child process sends a message using process.parentPort.postMessage().