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 };