William
William

Reputation: 13632

Express.js shutdown hook

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

Upvotes: 47

Views: 20879

Answers (4)

Jonathan
Jonathan

Reputation: 16349

The express team recommends the terminus package:

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

Upvotes: 2

Tom Saleeba
Tom Saleeba

Reputation: 4217

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}));

Upvotes: 1

alessioalex
alessioalex

Reputation: 63653

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

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

Upvotes: 12

maerics
maerics

Reputation: 156374

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

Upvotes: 47

Related Questions