When using node.js cluster, how to access a worker’s environment when it dies?

I'm using node.js cluster module to create worker processes. And I set a custom variable in each worker's environment as I fork it.

I need to read that custom variable when a worker dies, but when a worker dies, I can't access its environment object anymore.

This is what I tried so far:

var cluster = require('cluster'),
    os = require('os');

if (cluster.isMaster) {

    cluster.on('exit', function (worker, code, signal) {

        console.log('worker ' + worker.process.pid + ' died');

        var x = {
            workerId: worker.process.env.workerId // This is undefined.
        };
        cluster.fork(x);
    });

    for (var i = 0; i < os.cpus().length; i++) {
        var x = {
            workerId: i
        };
        cluster.fork(x);
    }

}
else {
    console.log("workerId: ", process.env.workerId);

    // simulate an exeption:
    throw "fakeError";

}

I know that's not gonna work, my question is: how to access to latest state of a worker's envoronment right before its death?

Leave a Reply

Your email address will not be published. Required fields are marked *