What is close-with-grace?
The 'close-with-grace' npm package helps manage graceful shutdowns in Node.js applications. It allows you to handle termination signals and perform cleanup tasks before the application exits, ensuring that resources are properly released and ongoing operations are completed.
What are close-with-grace's main functionalities?
Graceful Shutdown on SIGINT
This feature allows the application to handle the SIGINT signal (usually triggered by Ctrl+C) and perform cleanup tasks before shutting down. The provided code sample demonstrates how to set up a graceful shutdown with a delay and cleanup logic.
const closeWithGrace = require('close-with-grace');
const closeListeners = closeWithGrace({ delay: 500 }, async ({ err }) => {
if (err) {
console.error('Error during shutdown', err);
}
console.log('Cleaning up before shutdown...');
await new Promise(resolve => setTimeout(resolve, 100));
console.log('Cleanup complete.');
});
process.on('SIGINT', () => {
console.log('Received SIGINT');
closeListeners.uninstall();
});
Handling Multiple Signals
This feature allows the application to handle multiple termination signals (e.g., SIGTERM and SIGINT) and perform cleanup tasks before shutting down. The provided code sample demonstrates how to set up graceful shutdown handling for both SIGTERM and SIGINT signals.
const closeWithGrace = require('close-with-grace');
const closeListeners = closeWithGrace({ delay: 500 }, async ({ err }) => {
if (err) {
console.error('Error during shutdown', err);
}
console.log('Cleaning up before shutdown...');
await new Promise(resolve => setTimeout(resolve, 100));
console.log('Cleanup complete.');
});
process.on('SIGTERM', () => {
console.log('Received SIGTERM');
closeListeners.uninstall();
});
process.on('SIGINT', () => {
console.log('Received SIGINT');
closeListeners.uninstall();
});
Custom Cleanup Logic
This feature allows the application to define custom cleanup logic that will be executed before the application shuts down. The provided code sample demonstrates how to set up a graceful shutdown with custom cleanup logic and a delay.
const closeWithGrace = require('close-with-grace');
const closeListeners = closeWithGrace({ delay: 1000 }, async ({ err }) => {
if (err) {
console.error('Error during shutdown', err);
}
console.log('Performing custom cleanup...');
// Custom cleanup logic here
await new Promise(resolve => setTimeout(resolve, 500));
console.log('Custom cleanup complete.');
});
Other packages similar to close-with-grace
graceful-shutdown
The 'graceful-shutdown' package provides similar functionality for handling graceful shutdowns in Node.js applications. It allows you to register shutdown handlers and ensures that cleanup tasks are completed before the application exits. Compared to 'close-with-grace', 'graceful-shutdown' offers a more straightforward API but may lack some advanced features.
node-graceful-shutdown
The 'node-graceful-shutdown' package helps manage graceful shutdowns by providing a mechanism to handle termination signals and perform cleanup tasks. It is similar to 'close-with-grace' in terms of functionality but offers a different API design. 'node-graceful-shutdown' focuses on simplicity and ease of use.
http-terminator
The 'http-terminator' package is designed to facilitate graceful shutdowns of HTTP servers in Node.js. It ensures that all ongoing requests are completed before the server shuts down. While 'http-terminator' is more specialized for HTTP servers, 'close-with-grace' offers a more general-purpose solution for handling various types of cleanup tasks.
close-with-grace
Exit your process, gracefully (if possible) - for Node.js
Install
npm i close-with-grace
Usage
const closeWithGrace = require('close-with-grace')
closeWithGrace({ delay: 500 }, async function ({ signal, err, manual }) {
if (err) {
console.error(err)
}
await closeYourServer()
})
closeWithGrace({ delay: false }, () => await somethingUseful())
Injecting custom logger
const closeWithGrace = require('close-with-grace')
closeWithGrace(
{
delay: 500,
logger: { error: (m) => console.error(`[close-with-grace] ${m}`) }
},
async function ({ signal, err, manual }) {
if (err) {
console.error(err)
}
await closeYourServer()
})
closeWithGrace({ logger: false }, () => await somethingUseful())
Example with Fastify
import fastify from 'fastify'
import closeWithGrace from 'close-with-grace'
const app = fastify()
closeWithGrace(async function ({ signal, err, manual }) {
if (err) {
app.log.error({ err }, 'server closing with error')
} else {
app.log.info(`${signal} received, server closing`)
}
await app.close()
})
await app.listen()
API
closeWithGrace([opts], fn({ err, signal, manual }))
closeWithGrace
adds a global listeners to the events:
process.once('SIGHUP')
process.once('SIGINT')
process.once('SIGQUIT')
process.once('SIGILL')
process.once('SIGTRAP')
process.once('SIGABRT')
process.once('SIGBUS')
process.once('SIGFPE')
process.once('SIGSEGV')
process.once('SIGUSR2')
process.once('SIGTERM')
process.once('uncaughtException')
process.once('unhandledRejection')
process.once('beforeExit')
In case one of them is emitted, it will call the given function.
If it is emitted again, it will terminate the process abruptly.
opts
fn({ err, signal, manual } [, cb])
Execute the given function to perform a graceful close.
The function can either return a Promise
or call the callback.
If this function does not error, the process will be closed with
exit code 0
.
If the function rejects with an Error
, or call the callback with an
Error
as first argument, the process will be closed with exit code
1
.
return values
Calling closeWithGrace()
will return an object as formed:
close()
: close the process, the manual
argument will be set to
true.
uninstall()
: remove all global listeners.
License
MIT