node.js - 使用 express 在 nodejs 服务器关闭时执行代码

标签 node.js express

有没有办法在 node.js 进程退出之前在 Node.js Express 中执行一段代码,而不管它是由于抛出错误,还是按 Ctrl+C 或任何其他原因?

最佳答案

您正在寻找退出事件。来自文档:

Emitted when the process is about to exit. This is a good hook to perform constant time checks of the module's state (like for unit tests). The main event loop will no longer be run after the 'exit' callback finishes, so timers may not be scheduled.

它会被实现为

process.on('exit', function() {
    console.log('About to close');
});

值得一提的是,如果不知道退出或异常的原因,尝试操作数据通常不是一个好主意。如果您不知道哪里出了问题,最好重新开始,而不是尝试用很可能是 FUBAR 的东西来完成某事。

关于node.js - 使用 express 在 nodejs 服务器关闭时执行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20820884/

相关文章:

node.js - "No listeners detected"验证错误 Mongoose 和 Mocha

javascript - 如何确定深度过时/弃用包 (NPM) 的路径?

node.js - 编写一个带有变量值名称的 ini 键

c++ - Windows 上的另一个 node-gyp 错误或实际编码错误?

node.js - 如何托管静态登陆页面并在同一 Node 服务器上使用react?

javascript - Dropping Collection后,保存第一条记录时重新创建了Collection,但为什么它的索引没有?

node.js - Lint-staged 找不到与 glob 匹配的暂存文件

javascript - 强制不同的 npm 模块共享相同的依赖

javascript - 通过 XMLHttpRequest 将纯文本发送到 Express 服务器

node.js -/view 和/lib 文件夹之间的区别?