2011-12-14 64 views
20

在Express.js中,是否有一些設置應用程序關閉時執行的回調函數?Express.js關機鉤子

+0

下面的答案並不在每天活動很有用,你正在尋找[這](https://stackoverflow.com/questions/14031763/doing-a-cleanup-action- just-before-node-js-exits) - process.on('SIGINT',()=> {...}) – Midas 2017-06-23 21:35:11

回答

20

你可以使用Node.js的core process 'exit' event像這樣:

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

當然,主事件循環將停止運行,退出函數返回,所以你不能從內安排任何計時器或回調後功能(例如,任何I/O必須是同步的)。

1

如果您需要在當前範圍內訪問的東西,你可以bind()像這樣的回答:https://stackoverflow.com/a/14032965/1410035,但你可能要綁定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}));