在生产中运行我的Express应用程序时,我希望在其进程被终止时(即发送SIGTERM或SIGINT)正常关闭服务器.
这是我的代码的简化版本:
const express = require('express');
const app = express();
app.get('/', (req, res) => res.json({ ping: true }));
const server = app.listen(3000, () => console.log('Running…'));
setInterval(() => server.getConnections(
(err, connections) => console.log(`${connections} connections currently open`)
), 1000);
process.on('SIGTERM', shutDown);
process.on('SIGINT', shutDown);
function shutDown() {
console.log('Received kill signal, shutting down gracefully');
server.close(() => {
console.log('Closed out remaining connections');
process.exit(0);
});
setTimeout(() => {
console.error('Could not close connections in time, forcefully shutting down');
process.exit(1);
}, 10000);
}
Run Code Online (Sandbox Code Playgroud)
当我在浏览器中运行它并调用URL http:// localhost:3000 /时,setInterval函数中的日志语句将继续打印"1个当前打开的连接",直到我实际关闭浏览器窗口.即使关闭标签,显然也会保持连接打开. …