End all worker threads after the first one ends in Node.js

Solution 1:

There are a couple of things you need to change:

  • Use cluster.on instead of process.on, as process.on is for the child process, not the parent process.
  • Use child.process.kill() instead of child.kill().
const cluster = require('cluster')
const os = require('os')

if ( cluster.isMaster ) {

    let children = []
    for ( let i = 0; i < os.cpus().length; i++ ) {
        children.push(cluster.fork())
    }
    
    cluster.on('message', (worker, msg) => {
        if (msg.command = 'shutdown') {
            // Kill every cluster worker
            children.forEach(child => {
                child.process.kill()
            })
        }
    })

} else {

    console.log('I am worker #' + cluster.worker.id)
    let time = Date.now()
    while ( Date.now() < time + cluster.worker.id * 1000 ) {
        // do nothing for some time
    }
    console.log('I am worker #' + cluster.worker.id + ' and I am done')
    process.send({command: 'shutdown'})
}