Created
June 4, 2019 01:19
-
-
Save alex-taxiera/b1d0263c9df210d48673f9073be75036 to your computer and use it in GitHub Desktop.
Simple Node Child Process Broadcasting
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
process.on('message', (message) => { | |
console.log('child received:', message) | |
process.send(message) // echo the message back to parent | |
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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