Zero Dependency utility to exit NodeJs gracefully
npm install nexitConstructor parameters
| Parameter | Default | Description |
|---|---|---|
| options.shutdownDelay | 30000 | shutdown delay(ms) |
| options.exitDelay | 300 | exit delay(ms) |
const Nexit = require('nexit');
new Nexit.Nexit();or
import { Nexit } from 'nexit';
new Nexit();This library aims to delay process exit by a configurable amount of time to let service/traffic orchestrator to stop routing active traffic so that the process can be killed safely.
SIGINT,SIGTERManduncaughtExceptionsignals- start a timer with
shutdownDelayafter catching one of the signals above. - fire an event with
NEXIT_SHUTDOWNto let application know about the state
application can use this event for its
healthzroute as below.
- once
shutdownDelaytimer is expired, start a new timer withexitDelay - fire an event with
NEXIT_EXITto let application know about the state - at this point, application may exit on its own at any time if node event loop is fully cleared
- once
exitDelaytimer is expired, application will be killed forcefully byprocess.exitcommand
Simple healthz route implementation for ExpressJs.
const express = require('express');
const Nexit = require('nexit');
const app = express();
const nexit = new Nexit.Nexit();
nexit.on(Nexit.NEXIT_SHUTDOWN, (err, signal) => {
console.log(`server is shutting down signal: ${signal}`, err);
app.set('isShuttingDown', true);
});
nexit.on(Nexit.NEXIT_EXIT, () => {
console.log('server is exiting...');
});
app.get('/healthz', (req, res) => {
const isShuttingDown = app.get('isShuttingDown');
if (isShuttingDown) {
res.status(503).send({
message: 'shutting down',
});
return;
}
res.status(200).send({
message: 'ok',
});
});
app.listen(8080);See ./demo for a working example;
cd ./demo
npm install
node index.js