Node.js process doesn’t die on exit (ctrl+c)
Hello all,
Back in action with some uber simple node.js suggestions:
I bet that everybody have experimented the frustration of having this error:
EADDRINUSE, Address already in use
The reason is pretty simple, we quitted from the terminal without properly killing the node.js process. Till here everything plain and simple.
Then what to do to avoid this frustrating behavior…
Simply add to your server.js (bin/www if you are using express) this terminator that i found on openshift stack:
// first create a generic "terminator"
terminator = function(sig){
if (typeof sig === "string") {
console.log('%s: Received %s - terminating sample app ...',
Date(Date.now()), sig);
process.exit(1);
}
console.log('%s: Node server stopped.', Date(Date.now()) );
};
// then implement it for every process signal related to exit/quit
['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT',
'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'
].forEach(function(element, index, array) {
process.on(element, function() { terminator(element); });
});
..not only it works with CTRL+C exits, but it’s a collection of differents exit signals you can encounter. Delicious!
Extra tip: If you are quitting your app with CTRL+C could be an exception, but if you are new to the node.js scenario and you are using that method to update your server then i would like to suggestion nodemon, a delicious npm library that will restart your node.js on file change for you (and give you the additional ability of manual restart simply writing rs in the terminal window!)
# instead of using node server.js use nodemon! (it works with express too)
nodemon server.js
# file change
# automatic restart!
rs
# manual restart invoked
No comments yet.