1

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?

1 Answer 1

2

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.

2
  • Thanks, but I still not get it, how can I trigger infohandler.saveinfo function?
    – Kuan
    May 26, 2015 at 23:23
  • @Kuan Call it where it says "your clean up code". Make sure to only perform synchronous operations in there.
    – TimWolla
    May 26, 2015 at 23:51

Your Answer

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

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