Node.JS Shutdown Hook

700 Software picture 700 Software · Mar 22, 2011 · Viewed 8.7k times · Source

Is it possible to intercept the default kill signal and use it as a command for a graceful shutdown? This is for Solaris SMF. The easiest way to have a stoppable service that I have found is to set :kill as the shutdown script and then to add a shutdown hook in Java. In this case, I want to do it for Node.JS. How should I do it?

Edit: The purpose is to

  1. Stop receiving new requests.
  2. Give existing callbacks a few seconds to finish.
  3. Write some information to stderr.

@alienhard's first suggestion was to use process.on('exit'... but it seems that I would not be able to accomplish number 2 with this method.

Answer

alienhard picture alienhard · Mar 22, 2011

There is an exit event: http://nodejs.org/docs/v0.3.1/api/process.html#event_exit_

process.on('exit', function() {
  console.log('About to exit.');
});

Edit: An alternative that could work for you, is instead of killing the process, sending a signal like SIGUSR1 (kill -s SIGUSR1), and then listening for this signal (see link posted by @masylum in another answer) and after you are done or some time has elapsed explicitly terminate with process.exit().