Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kill NodeJS child processes

During development I make mistakes in my NodeJS project. Mistakes lead to an error message like this.

events.js:85
      throw er; // Unhandled 'error' event
            ^
Error: listen EADDRINUSE
    at exports._errnoException (util.js:742:11)
    at Server._listen2 (net.js:1148:14)
    at listen (net.js:1170:10)
    at net.js:1253:9
    at dns.js:82:18
    at process._tickCallback (node.js:343:11)

No problem, I hit ctrl+C and restart the process but I see some spawned child processes still active. How can I kill all processes spawned by the root process?

Sample code:

module.exports.start = function(options) {
  gulp.watch(['*.js'], onServerRestart);
  onServerRestart();

  var server;
  function onServerRestart(e) {
    if (server) server.kill();
    server = require('child_process').spawn("node", ['--harmony', './server.js'], {stdio: "inherit", cwd: process.cwd() });
  };
};
like image 433
xpepermint Avatar asked Nov 01 '22 19:11

xpepermint


1 Answers

Adding this

  process.on('uncaughtException', function(err) {
    console.log(err);
    server.kill();
    process.kill();
  });

solves the problem. Any suggestions how to handle this in your app?

like image 122
xpepermint Avatar answered Nov 12 '22 17:11

xpepermint