Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2016
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1. import gracefulShutdown from './tools/graceful-shutdown';
  2.  
  3. const server = app.listen(config.port, () => {
  4. console.log(`Server is running`);
  5. });
  6.  
  7. app.use(gracefulShutdown(server));
  8.  
  9. function gracefulShutdownMiddleware(server) {
  10.  
  11. let shuttingDown = false;
  12. const forceTimeout = 10 * 1000; // giving the app 10 seconds to shutdown gracefully
  13.  
  14.  
  15. process.on('SIGTERM', gracefulExit); // listen for TERM signal (e.g. kill)
  16. process.on ('SIGINT', gracefulExit); // listen for INT signal (e.g. Ctrl-C)
  17.  
  18. function gracefulExit() {
  19.  
  20. if (shuttingDown) return;
  21. shuttingDown = true;
  22. console.log('Received kill signal (SIGTERM), shutting down');
  23.  
  24. setTimeout(function () {
  25. console.log('Could not close connections in time, forcefully shutting down');
  26. process.exit(1);
  27. }, forceTimeout);
  28.  
  29. server.close(function () {
  30. console.log('Closed out remaining connections.');
  31. process.exit();
  32. });
  33.  
  34. }
  35.  
  36. function middleware(req, res, next) {
  37. if (!shuttingDown) return next()
  38. res.set('Connection', 'close')
  39. res.status(503).send('Server is in the process of restarting.')
  40. }
  41.  
  42. return middleware
  43.  
  44. }
  45.  
  46. export default gracefulShutdownMiddleware;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement