Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.JS Shutdown Hook

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.

like image 541
700 Software Avatar asked Mar 22 '11 19:03

700 Software


2 Answers

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().

like image 52
alienhard Avatar answered Oct 07 '22 06:10

alienhard


The only thing that comes to my mind is using signal events.

http://nodejs.org/docs/v0.3.1/api/process.html#signal_Events

like image 43
masylum Avatar answered Oct 07 '22 06:10

masylum