Over-thinking #3: Restarting a node.js process

Sure, you could use something like forever but what if you want things as self contained as possible?

It’s very ugly and breaks stdio, but it works!

var cluster = require('cluster');
var _ = require('underscore');
var spawn = require('child_process').spawn;
if(cluster.isMaster) {
  //var cluster_args = 
  var runningragnarok = false;
  var msghandler = function(msg) {
    if(msg === 'rebirth') {
      _.each(cluster.workers, function(v) {
        v.kill();
      });
    }
    if(msg === 'ragnarok' && runningragnarok === false) {
      runningragnarok = true;
      var nargs = process.argv;
      nargs.splice.apply(nargs, [1, 0].concat(process.execArgv));
      if(!_.contains(process.argv, '--regnarok')) {
        nargs.push('--ragnarok');
        nargs.push(5000);
      }
      _.each(cluster.workers, function(w) { w.kill(); });
      spawn(nargs[0], nargs.slice(1), {detached: true, stdio: ['ignore', 'ignore', 'ignore']});
      process.kill(process.pid);
    }

    if(msg === 'heatdeath') {
      process.kill(process.pid);
    }
  };

  cluster.on('exit', function() { if(runningragnarok) return; cluster.fork().on('message', msghandler); });

  setTimeout(function() {
    _.each([1,2,3,4,5], function() {
      var f = cluster.fork()
      f.on('message', msghandler);
    })
  }, 5000);
  //_.find(process.argv, function(v, i, a) { return i > 0 && a[i-1] === '--ragnarok'; }) || 5000
  return;
}