How to kill all child processes on exit?

How to kill all child processes (spawned using child_process.spawn) when node.js process exit?

I think the only way is to keep a reference to the ChildProcess object returned by spawn, and kill it when you exit the master process.

A small example:

var spawn     = require('child_process').spawn;
var children  = [];

process.on('exit', function() {
  console.log('killing', children.length, 'child processes');
  children.forEach(function(child) {
    child.kill();
  });
});

children.push(spawn('/bin/sleep', [ '10' ]));
children.push(spawn('/bin/sleep', [ '10' ]));
children.push(spawn('/bin/sleep', [ '10' ]));

setTimeout(function() { process.exit(0) }, 3000);

To add to @robertklep's answer:

If, like me, you want to do this when Node is being killed externally, rather than of its own choice, you have to do some trickery with signals.

The key is to listen for whatever signal(s) you could be killed with, and call process.exit(), otherwise Node by default won't emit exit on process!

var cleanExit = function() { process.exit() };
process.on('SIGINT', cleanExit); // catch ctrl-c
process.on('SIGTERM', cleanExit); // catch kill

After doing this, you can just listen to exit on process normally.

The only issue is SIGKILL can't be caught, but that's by design. You should be killing with SIGTERM (the default) anyway.

See this question for more.