utilityProcess
utilityProcess
使用 Node.js 和 Message 端口创建了一个子进程。 它提供一个相当于 Node.js 的 child_process.fork
API,但使用 Chromium 的 Services API 代替来执行子进程。
Process: Main
方法
utilityProcess.fork(modulePath[, args][, options])
modulePath
string - 作为子进程执行入口的脚本文件路径。args
string[] (可选) - 字符串参数列表,在子进程中可以使用process.argv
。
Returns UtilityProcess
Class: UtilityProcess
UtilityProcess
的实例代表 Chromium 派生子进程与 Node.js 的结合。
UtilityProcess
是一个 EventEmitter。
实例方法
child.postMessage(message, [transfer])
message
anytransfer
MessagePortMain[] (可选)
Send a message to the child process, optionally transferring ownership of zero or more MessagePortMain
objects.
例如:
// 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
代表子进程的进程 ID (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
代表子进程的 stdout 。 If the child was spawned with options.stdio[1] set to anything other than 'pipe', then this will be 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
A NodeJS.ReadableStream | null
代表子进程的 stderr 。 If the child was spawned with options.stdio[2] set to anything other than 'pipe', then this will be null
. 当子进程退出,在 exit
事件处罚之后,值为 null
。
实例事件
Event: 'spawn'
子进程成功生成后触发一次。
Event: 'error' Experimental
返回:
type
string - Type of error. 以下值之一:FatalError
location
string - Source location from where the error originated.report
string -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.
Event: 'exit'
返回:
code
number - Contains the exit code for the process obtained from waitpid on POSIX, or GetExitCodeProcess on Windows.
进程结束之后触发。
Event: 'message'
返回:
message
any
Emitted when the child process sends a message using process.parentPort.postMessage()
.