我一直在尝试终止进程之前执行异步操作。
说“终止”是指终止的所有可能性:
ctrl+c
据我所知,
exit
事件仅用于同步操作。阅读Nodejs文档后,我发现
beforeExit
事件用于异步操作BUT:有什么建议?
最佳答案
您可以捕获信号并在退出之前执行异步任务。这样的事情会在退出之前调用terminator()函数(甚至代码中的javascript错误):
process.on('exit', function () {
// Do some cleanup such as close db
if (db) {
db.close();
}
});
// catching signals and do something before exit
['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT',
'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'
].forEach(function (sig) {
process.on(sig, function () {
terminator(sig);
console.log('signal: ' + sig);
});
});
function terminator(sig) {
if (typeof sig === "string") {
// call your async task here and then call process.exit() after async task is done
myAsyncTaskBeforeExit(function() {
console.log('Received %s - terminating server app ...', sig);
process.exit(1);
});
}
console.log('Node server stopped.');
}
添加评论中要求的详细信息: