utilityProcess
utilityProcess
建立一個啟用 Node.js 和訊息埠的子程序。它提供了 Node.js 中 child_process.fork
API 的等效功能,但改為使用 Chromium 的 Services API 來啟動子程序。
程序:主程序
方法
utilityProcess.fork(modulePath[, args][, options])
modulePath
字串 - 應作為子程序中進入點執行的腳本路徑。args
字串陣列 (選填) - 字串引數列表,將在子程序中作為process.argv
提供。
類別:UtilityProcess
UtilityProcess
的實例代表具有 Node.js 整合的 Chromium 衍生子程序。
UtilityProcess
是一個 EventEmitter。
實例方法
child.postMessage(message, [transfer])
message
任何transfer
MessagePortMain[] (選填)
傳送訊息到子程序,選擇性地轉移零或多個 MessagePortMain
物件的所有權。
例如
// 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()
傳回 boolean
優雅地終止程序。在 POSIX 上,它使用 SIGTERM,但將確保程序在退出時被回收。如果終止成功,此函式傳回 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
})
注意: 您可以使用 pid
來判斷程序目前是否正在執行。
child.stdout
一個 NodeJS.ReadableStream | null
,表示子程序的 stdout。如果子程序在衍生時,options.stdio[1] 設定為 'pipe' 以外的任何值,則此值將為 null
。當子程序退出時,在發出 exit
事件後,該值為 null
。
// 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
一個 NodeJS.ReadableStream | null
,表示子程序的 stderr。如果子程序在衍生時,options.stdio[2] 設定為 'pipe' 以外的任何值,則此值將為 null
。當子程序退出時,在發出 exit
事件後,該值為 null
。
實例事件
事件:'spawn'
子程序成功衍生後發出。
事件:'error' 實驗性
傳回
type
字串 - 錯誤類型。以下值之一FatalError
location
字串 - 錯誤來源位置。report
字串 -Node.js 診斷報告
。
當子程序由於 V8 中不可繼續的錯誤而需要終止時發出。
無論您是否監聽 error
事件,exit
事件都會在子程序終止後發出。
事件:'exit'
傳回
code
數字 - 包含從 POSIX 上的 waitpid 或 Windows 上的 GetExitCodeProcess 取得的程序結束代碼。
子程序結束後發出。
事件:'message'
傳回
message
任何
當子程序使用 process.parentPort.postMessage()
傳送訊息時發出。