UNPKG

@mangar2/shutdown

Version:

Implements graceful shutdown

57 lines (50 loc) 1.64 kB
/** * @license * This software is licensed under the GNU LESSER GENERAL PUBLIC LICENSE Version 3. It is furnished * "as is", without any support, and with no warranty, express or implied, as to its usefulness for * any purpose. * * @author Volker Böhm * @copyright Copyright (c) 2020 Volker Böhm * @name Shutdown * @description * Shutdown is a small helper to safely shutdown serivces on SIGINT (ctrl-C) * A singelton calling a callback on SIGINT and provides a timeout if the callback does not finish in a period of time. * @example * const shutdown = require('shutdown'); * * shutdown(async () => { * await myClass.close(); * process.exit(0); * }); */ 'use strict' const FORCE_SHUTDOWN_TIMEOUT_IN_MILLISECONDS = 4000 var sigintCallback var timeout /** * @param {function} callback function called on sigint before shutdown * @param {number} [forceShutdownTimeoutInMilliseconds=FORCE_SHUTDOWN_TIMEOUT_IN_MILLISECONDS] * amount of milliseconds until shutdown is forced */ module.exports = (callback, forceShutdownTimeoutInMilliseconds) => { timeout = forceShutdownTimeoutInMilliseconds if (isNaN(timeout)) { timeout = FORCE_SHUTDOWN_TIMEOUT_IN_MILLISECONDS } sigintCallback = callback process.on('SIGINT', () => { if (sigintCallback !== undefined) { sigintCallback() } setTimeout((err) => { if (err) { console.error(err) } process.exit(1) }, timeout) }) process.on('SIGTERM', () => { process.exit(0) }) }