utilityProcess
utilityProcess
创建一个启用了 Node.js 和消息端口的子进程。它提供了 Node.js 中的 child_process.fork
API 的等效功能,但使用 Chromium 中的 Services API 启动子进程。
进程:主进程
方法
utilityProcess.fork(modulePath[, args][, options])
modulePath
string - 应该作为子进程中的入口点运行的脚本的路径。args
string[] (可选) - 将作为子进程中的process.argv
提供的字符串参数列表。
utilityProcess.fork
只能在 App
上发出 ready
事件后调用。
类:UtilityProcess
UtilityProcess
的实例表示具有 Node.js 集成的 Chromium 生成的子进程。
UtilityProcess
是一个 EventEmitter。
实例方法
child.postMessage(message, [transfer])
message
anytransfer
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
string - 错误的类型。 以下值之一致命错误
location
string - 错误源自的源位置。report
string -Node.js 诊断报告
。
当子进程由于 V8 中的不可继续错误而需要终止时发出。
无论您是否侦听 error
事件,子进程终止后都会发出 exit
事件。
事件:'exit'
返回
code
number - 包含从 POSIX 上的 waitpid 或 Windows 上的 GetExitCodeProcess 获取的进程的退出代码。
子进程结束后发出。
事件:'message'
返回
message
any
当子进程使用 process.parentPort.postMessage()
发送消息时发出。