I have a clustered node app, and I'm looking for a way to get state of all my workers from one request.
I use express to ask the masten but it's not express related. with one request, i would like to have something like this:
[
{
pid: 'xxxxxx',
state: 'I\'m fine'
},
{
pid: 'xxxxxx',
state: 'I\'m sick'
},
{
pid: 'xxxxxx',
state: 'I\'m fine'
},
]
To send express answer, I need to wait all worker answers, and concat them. But the question is: How to wait for a spécific answer from a worker instead of a simple listenner?
Here is a code sample of the clustered app. I'm trying to get the previous Json in request of http://localhost:8000/
import * as cluster from 'cluster';
import * as express from 'express';
if (cluster.isMaster) {
// Here is master
// we start by creating few workers
for (let i = 0; i < 4; i++) {
cluster.fork();
}
// for each worker, if we receive a message, we print it
for (const id in cluster.workers) {
if (cluster.workers.hasOwnProperty(id)) {
cluster.workers[id].on('message', (msg) => {
console.log(`[${cluster.workers[id].process.pid}] ${msg}`);
});
}
}
// create express server
const app = express();
app.get('/', (req, res) => {
// request from client
console.log('\nHow are you all?');
// for each workers
for (const id in cluster.workers) {
if (cluster.workers.hasOwnProperty(id)) {
// ask state
cluster.workers[id].send('howareyou');
// how to wait for answer?
}
}
// probably concat all answers here
// send result to client
res.setHeader('Content-Type', 'application/json');
res.json({question: 'How can I have state of all my workers?'});
});
app.listen(8000);
} else {
// Here is worker.
process.on('message', (message) => {
// When master ask state, send back random answer
if (message === 'howareyou') {
process.send(`I'm ${Math.random() * 100 < 75 ? 'fine' : 'sick'}`);
}
});
}
Thanks in advance :)