All Projects → porsager → prexit

porsager / prexit

Licence: WTFPL License
A graceful way to shutdown / handle process exit

Programming Languages

javascript
184084 projects - #8 most used programming language

version license

🚪 Prexit

A graceful way to shutdown / handle PRocess EXIT - way better than other *rexits

const prexit = require('prexit')

prexit((signal, code_or_err) => {
  // Do cleanup before shutdown
  // Return a promise to delay exit
  // set prexit.code to exit with non 0
  // eg prexit.code = 1
})

Here's a sample for shutting down an http server and database. First we stop the http server from accepting any new connections. Then we gracefully close the database connection to allow any pending queries to resolve.

prexit(async () => {
  await new Promise(r => server.close(r))
  await db.end({ timeout: 5 })
})

Prexit is a simple function that takes a callback. This will be called with the signal and exit code / error on the following process events.

beforeExit | uncaughtException | SIGTSTP | SIGQUIT | SIGHUP | SIGTERM | SIGINT

You can call prexit as many times as you'd like so you can do cleanup in the relevant places in your code. Prexit will await all promises that callbacks returns, and will ensure they are only called once. After all the promises finalizes prexit will call prexit.ondone() which defaults to calling process.exit(prexit.code).

If you need to do synchronous cleanup after any async cleanup and right before prexit.ondone is called, you can use prexit.last(fn)

prexit.last(() => {
  // This will run after any async handlers right 
  // before exit, meaning only sync cleanup
  // eg. (kill child processes)
})

You can also supply optional events to listen for as the first argument of prexit.

prexit('uncaughtException', (signal, err) => /* uncaughtException */ )
prexit(['SIGHUP', 'SIGTERM'], (signal, err) => /* SIGHUP | SIGTERM */ )
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].