Skip to content

Instantly share code, notes, and snippets.

@alex-taxiera
Created June 4, 2019 01:19
Show Gist options
  • Save alex-taxiera/b1d0263c9df210d48673f9073be75036 to your computer and use it in GitHub Desktop.
Save alex-taxiera/b1d0263c9df210d48673f9073be75036 to your computer and use it in GitHub Desktop.
Simple Node Child Process Broadcasting
process.on('message', (message) => {
console.log('child received:', message)
process.send(message) // echo the message back to parent
})
const { fork } = require('child_process')
const children = new Array(5)
for (let i = 4; i > -1; i--) {
children[i] = fork('./child.js')
children[i].sendMessage = (message) => {
return new Promise((resolve, reject) => {
children[i].messageListener = (message) => {
children[i].removeListener('message', children[i].messageListener)
resolve(message)
}
children[i].on('message', children[i].messageListener)
children[i].send(message)
})
}
}
Promise.all(children.map((child, i) => child.sendMessage(i)))
.then((results) => console.log('results:', results)) // results: [ 0, 1, 2, 3, 4 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment