worker.send(message[, sendHandle][, callback])


发送一个消息给工作进程或主进程,也可以附带发送一个handle。

主进程调用这个方法会发送消息给具体的工作进程。还有一个等价的方法是ChildProcess.send()

工作进程调用这个方法会发送消息给主进程。还有一个等价方法是process.send()

这个例子里面,工作进程将主进程发送的消息echo回去。

if (cluster.isMaster) {
  const worker = cluster.fork();
  worker.send('hi there');

} else if (cluster.isWorker) {
  process.on('message', (msg) => {
    process.send(msg);
  });
}

Send a message to a worker or master, optionally with a handle.

In the master this sends a message to a specific worker. It is identical to ChildProcess.send().

In a worker this sends a message to the master. It is identical to process.send().

This example will echo back all messages from the master:

if (cluster.isMaster) {
  const worker = cluster.fork();
  worker.send('hi there');

} else if (cluster.isWorker) {
  process.on('message', (msg) => {
    process.send(msg);
  });
}