cursor done.
This commit is contained in:
41
server/utils/shutdown.js
Normal file
41
server/utils/shutdown.js
Normal file
@@ -0,0 +1,41 @@
|
||||
const { closeDatabase } = require('../database');
|
||||
|
||||
function registerShutdown(server) {
|
||||
let isShuttingDown = false;
|
||||
|
||||
async function shutdown(reason) {
|
||||
if (isShuttingDown) return;
|
||||
isShuttingDown = true;
|
||||
|
||||
if (reason) {
|
||||
console.log(`\n收到 ${reason},正在关闭服务器...`);
|
||||
}
|
||||
|
||||
await new Promise((resolve) => {
|
||||
server.close(() => {
|
||||
console.log('HTTP 服务器已关闭');
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
|
||||
await closeDatabase();
|
||||
process.exit(reason === 'uncaughtException' || reason === 'unhandledRejection' ? 1 : 0);
|
||||
}
|
||||
|
||||
process.on('SIGINT', () => shutdown('SIGINT'));
|
||||
process.on('SIGTERM', () => shutdown('SIGTERM'));
|
||||
|
||||
process.on('uncaughtException', (err) => {
|
||||
console.error('未捕获的异常:', err);
|
||||
shutdown('uncaughtException');
|
||||
});
|
||||
|
||||
process.on('unhandledRejection', (reason) => {
|
||||
console.error('未处理的 Promise 拒绝:', reason);
|
||||
shutdown('unhandledRejection');
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
registerShutdown
|
||||
};
|
||||
Reference in New Issue
Block a user