Skip to content

Instantly share code, notes, and snippets.

@akirattii
Created January 26, 2018 07:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akirattii/a0014f6aa6533b0268256e3674653e2e to your computer and use it in GitHub Desktop.
Save akirattii/a0014f6aa6533b0268256e3674653e2e to your computer and use it in GitHub Desktop.
express: Implement a graceful shutdown handling `forever stop`
/*
Run server by forever with `--killSignal=SIGTERM`:
```
$ forever --killSignal=SIGTERM start ./server.js
```
Now `gracefulShutdown` function is called when you stop the server by `forever stop`:
```
$ forever stop
```
*/
const express = require('express');
app = express();
//...
const server = app.listen(3000);
//
// Graceful shutdown:
//
const gracefulShutdown = function() {
const ms = 2000;
logger.debug(`[server] gracefulShutdown: shutdown after ${ms} ms...`);
setTimeout(() => {
logger.debug(`[server] gracefulShutdown: aborting...`);
process.abort();
}, ms);
};
process.on('SIGTERM', gracefulShutdown); // for kill
process.on('SIGINT', gracefulShutdown); // for Ctrl+C
module.exports = app;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment