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
代表子程序的程序識別碼 (PID) 的 Integer | undefined
。直到子程序成功產生後,該值才為 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
代表子程序 stdout 的 NodeJS.ReadableStream | null
。如果子程序在產生時 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
代表子程序 stderr 的 NodeJS.ReadableStream | null
。如果子程序在產生時 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()
傳送訊息時發出。