'message' 事件


当 cluster 主进程接收任意工作进程发送的消息时触发。

参阅 child_process event: 'message'

在 Node.js v6.0 版本之前,此事件只接受 messagehandle 两个参数,而没有 worker 对象。

如果要兼容旧版本并且不需要工作进程对象的情况下,可以通过判断参数数量来实现兼容。

cluster.on('message', (worker, message, handle) => {
  if (arguments.length === 2) {
    handle = message;
    message = worker;
    worker = undefined;
  }
  // ...
});

Emitted when the cluster master receives a message from any worker.

See child_process event: 'message'.

Before Node.js v6.0, this event emitted only the message and the handle, but not the worker object, contrary to what the documentation stated.

If support for older versions is required but a worker object is not required, it is possible to work around the discrepancy by checking the number of arguments:

cluster.on('message', (worker, message, handle) => {
  if (arguments.length === 2) {
    handle = message;
    message = worker;
    worker = undefined;
  }
  // ...
});