3 回答

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超6個(gè)贊
最新情況:
process.on('exit')
SIGINT
process.exit()
process.stdin.resume();//so the program will not close instantlyfunction exitHandler(options, exitCode) { if (options.cleanup) console.log('clean'); if (exitCode || exitCode === 0) console.log(exitCode); if (options.exit) process.exit();}//do something when app is closingprocess.on('exit', exitHandler.bind(null,{cleanup:true})); //catches ctrl+c eventprocess.on('SIGINT', exitHandler.bind(null, {exit:true})); // catches "kill pid" (for example: nodemon restart)process.on('SIGUSR1', exitHandler.bind(null, {exit:true})); process.on('SIGUSR2', exitHandler.bind(null, {exit:true})); //catches uncaught exceptionsprocess.on('uncaughtException', exitHandler.bind(null, {exit:true}));

TA貢獻(xiàn)1772條經(jīng)驗(yàn) 獲得超6個(gè)贊
下面的腳本允許對(duì)所有退出條件都有一個(gè)處理程序。它使用一個(gè)特定于應(yīng)用程序的回調(diào)函數(shù)來執(zhí)行自定義清理代碼。
Clearup.js
// Object to capture process exits and call app specific cleanup function
function noOp() {};
exports.Cleanup = function Cleanup(callback) {
// attach user callback to the process event emitter
// if no callback, it will still exit gracefully on Ctrl-C
callback = callback || noOp;
process.on('cleanup',callback);
// do app specific cleaning before exiting
process.on('exit', function () {
process.emit('cleanup');
});
// catch ctrl+c event and exit normally
process.on('SIGINT', function () {
console.log('Ctrl-C...');
process.exit(2);
});
//catch uncaught exceptions, trace, then exit normally
process.on('uncaughtException', function(e) {
console.log('Uncaught Exception...');
console.log(e.stack);
process.exit(99);
});
};
這段代碼截取了未識(shí)別的異常、Ctrl-C和正常的退出事件。然后,它在退出之前調(diào)用一個(gè)可選的用戶清理回調(diào)函數(shù),用一個(gè)對(duì)象處理所有退出條件。
該模塊只是擴(kuò)展Process對(duì)象,而不是定義另一個(gè)事件發(fā)射器。如果沒有應(yīng)用程序特定的回調(diào),清理默認(rèn)為無OP函數(shù)。當(dāng)Ctrl-C退出時(shí),子進(jìn)程仍在運(yùn)行,這對(duì)我的使用來說已經(jīng)足夠了。
您可以根據(jù)需要輕松添加其他退出事件,如SIGHUP。注意:根據(jù)NodeJS手冊,SIGKILL不能有偵聽器。下面的測試代碼演示了使用Clearup.js的各種方法
// test cleanup.js on version 0.10.21
// loads module and registers app specific cleanup callback...
var cleanup = require('./cleanup').Cleanup(myCleanup);
//var cleanup = require('./cleanup').Cleanup(); // will call noOp
// defines app specific callback...
function myCleanup() {
console.log('App specific cleanup code...');
};
// All of the following code is only needed for test demo
// Prevents the program from closing instantly
process.stdin.resume();
// Emits an uncaught exception when called because module does not exist
function error() {
console.log('error');
var x = require('');
};
// Try each of the following one at a time:
// Uncomment the next line to test exiting on an uncaught exception
//setTimeout(error,2000);
// Uncomment the next line to test exiting normally
//setTimeout(function(){process.exit(3)}, 2000);
// Type Ctrl-C to test forced exit
- 3 回答
- 0 關(guān)注
- 535 瀏覽
添加回答
舉報(bào)