如何在退出时执行asynchronous操作

我一直试图在我的进程终止之前执行asynchronous操作。

说'终止'我的意思是一切终止的可能性:

  • ctrl+c
  • 未捕获的exception
  • 崩溃
  • 代码结束
  • 什么..]

据我所知, exit事件,但同步操作。

阅读Nodejs文档我发现beforeExit事件是为asynchronous操作但是:

“beforeExit”事件不是针对导致显式终止的条件发出的,例如调用process.exit()或未捕获的exception。

除非意图安排额外的工作,否则“beforeExit”不应该被用作“退出”事件的替代scheme。

有什么build议么?

在退出之前,您可以捕获信号并执行asynchronous任务。 像这样的东西会退出之前调用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.'); } 

添加评论中请求的详细信息

  • 信号从节点的文档中解释,这个链接指的是标准的POSIX信号名称
  • 信号应该是string。 但是,我已经看到其他人已经做了检查,所以可能有一些我不知道的其他意外信号。 只需要在调用process.exit()之前确定。 我觉得无论如何也不需要太多的时间来做检查。
  • 对于db.close(),我想这取决于你使用的驱动程序。 无论是asynchronous同步。 即使它是asynchronous的,并且在dbclosures之后你不需要做任何事情,那么它应该没问题,因为asynchronousdb.close()只是发出closures事件,事件循环会继续处理它,不pipe你的服务器是否退出。