5

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() });
  };
};
xpepermint
  • 35,055
  • 30
  • 109
  • 163
  • If you are using Linux, `ps xau | grep node` and then kill the required process(es) – Salem Aug 07 '14 at 15:55
  • @Salem For sure but how do I handle this inside nodejs process? :) – xpepermint Aug 07 '14 at 16:10
  • oh sorry :) Try to send kill signal to it (`server.kill('SIGKILL')`) – Salem Aug 07 '14 at 16:24
  • @Salem I know how to manually handle this but as I sad, in case of an error, child processes are not automatically killed. – xpepermint Aug 07 '14 at 16:38
  • I've never killed other node process from within Node, so my only recommendation is to use something like `node-supervisor` to manage the node processes. I guess you could use `child-process` to execute something like Salem's first suggestion though. – Tony Aug 07 '14 at 16:44

2 Answers2

1

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?

xpepermint
  • 35,055
  • 30
  • 109
  • 163
1

This means, even though you may think you exited all servers, one is indeed still running, and that maybe the server you are trying to access.

Therefore go to your terminal and type the following:

killall node

This should solve it.

BAM.

VickenCode
  • 305
  • 2
  • 12