45

In Express.js, is there someway of setting a callback function to be executed when the application shuts down?

1
  • 2
    The below answers are not useful in every day activity, you're looking for this - process.on('SIGINT', () => { ...})
    – mattyb
    Jun 23, 2017 at 21:35

4 Answers 4

45

You could use the node.js core process 'exit' event like so:

process.on('exit', function() {
  // Add shutdown logic here.
});

Of course, the main event loop will stop running after the exit function returns so you can't schedule any timers or callbacks from within that function (e.g. any I/O must be synchronous).

3
11

There is process.on('exit', callback):

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

The express team recommends the terminus package:

https://expressjs.com/en/advanced/healthcheck-graceful-shutdown.html

0
1

If you need to access something in the current scope, you can bind() like in this answer: https://stackoverflow.com/a/14032965/1410035 but you might want to bind this.

function exitHandler(options, err) {
    if (options.cleanup) console.log('clean');
    if (err) console.log(err.stack);
    if (options.exit) process.exit();
}

process.on('exit', exitHandler.bind(null,{cleanup:true}));
1
  • Or just use an arrow function. Its scope is wherever it's declared. const exitHandler = (options, err) => {...} Nov 20, 2018 at 3:49

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.