I am looking to bootstrap a node cluster with a start and stop methods.
I wanted to write something similar to:
myCluster.start().then(()=>{
return myCluster.stop().then(()=>{console.log('smooth stop! nice.')});
}).catch(err=>{console.log('something went wrong')});
How can i exactly tell when all my workers are running?
PS: It doesn't have to be with promises.
I managed to engineer a solution by sending a message from a worker to the master as soon as the worker is listening:
private sendMaster(pid: number, msg: ClusterMessage) {
process.send({ pid, msg });
}
self.server.listen(self.options.port, () => {
self.sendMaster(process.pid, ClusterMessage.WORKER_LISTENING);
resolve();
}).on('error', () => {
logError('Failed to start the server on port %O', self.options.port);
reject();
});
And in the master code i would grab the messages like this:
cluster.on('message', (worker, data) => {
logInfo('Process %O listening on port %O', data.pid, self.options.port);
self.startedWorkersCount++;
if (self.startedWorkersCount === self.options.workers) {
logInfo('Server ready');
resolve(self.startedWorkersCount);
}
});
You can check my code with more detail here