forked from serby/express-graceful-shutdown
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
38 lines (30 loc) · 1.06 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
function createMiddleware(server, opts) {
var shuttingDown = false,
options = { logger: console, forceTimeout: 30000, ...opts }
// Graceful shutdown taken from: http://blog.argteam.com/
process.on('SIGTERM', gracefulExit)
function gracefulExit() {
// Don't bother with graceful shutdown on development to speed up round trip
if (!process.env.NODE_ENV) return process.exit(1)
if (shuttingDown) return
shuttingDown = true
options.logger.info('Received kill signal (SIGTERM), shutting down')
setTimeout(function() {
options.logger.error(
'Could not close connections in time, forcefully shutting down'
)
process.exit(1)
}, options.forceTimeout).unref()
server.close(function() {
options.logger.info('Closed out remaining connections.')
process.exit()
})
}
function middleware(req, res, next) {
if (!shuttingDown) return next()
res.set('Connection', 'close')
res.status(503).send('Server is in the process of restarting.')
}
return middleware
}
module.exports = createMiddleware