1

假设我编写了一个模块 handler.js 作为 Express.js 中间件:

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;

在 app.js 中,我导入了这个 handler.js:

var handler = require("handler");

我想在服务器关闭之前将一些信息保存到文件中。我怎样才能做到这一点?

4

1 回答 1

2

用于process.on绑定到exit事件。此事件在正常关闭时调用:

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

如果你想捕获特定的信号(例如默认使用 kill(1) 发送的 SIGTERM)绑定到信号的名称:

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

请注意,这将禁用默认操作(关闭)。确保process.exit在那里手动调用。

于 2015-05-26T22:43:04.480 回答