Skip to content

Instantly share code, notes, and snippets.

@tibawatanabe
Last active September 9, 2018 03:21
Show Gist options
  • Save tibawatanabe/c37ff4b1eed63f8c646489f68dcc3be2 to your computer and use it in GitHub Desktop.
Save tibawatanabe/c37ff4b1eed63f8c646489f68dcc3be2 to your computer and use it in GitHub Desktop.
Example of how to exchange messages between node processes
// Sending messages
if (cluster.isMaster) {
// It's also possible to get workers by iterating over `cluster.workers` hash map:
// https://nodejs.org/api/cluster.html#cluster_cluster_workers
const worker = cluster.fork();
worker.send('Sending message to worker');
} else {
process.send('Sending message to master');
}
// Receiving messages
if (cluster.isMaster) {
const worker = ... // getting a worker
worker.on('message', fromWorker => { /* handle worker's message */ });
} else {
process.on('message', fromMaster => { /* handle master's message */ })
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment