Kuan
Kuan

Reputation: 11389

How to perform an action on shutdown?

Suppose I write a module handler.js as Express.js middleware:

var info = {};

infohandler.setinfo = function(i){ info[i] = Math.random(); }
infohandler.saveinfo = function(){ fs.writeFileSync("info.json", info); }

function handler(req, res, next){ // here are some operation call to infohandler according to req. }

module.exports = handler;

And in app.js I import this handler.js:

var handler = require("handler");

I want to save some information to a file right before server shutdown. How can I do this?

Upvotes: 1

Views: 1026

Answers (1)

TimWolla
TimWolla

Reputation: 32681

Use process.on to bind to the exit event. This event is called on a graceful shutdown:

process.on('exit', function () {
    // your clean up code
});

If you want to catch specific signals (such as SIGTERM which is send by default using kill(1)) bind to the name of the signal:

process.on('SIGTERM', function () { /* ... */ });

Note that this will disable the default action (shutdown). Make sure to manually call process.exit in there.

Upvotes: 2

Related Questions