prexit
TypeScript icon, indicating that this package has built-in type declarations

2.2.0 • Public • Published

version license

🚪 Prexit

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

import prexit from 'prexit'

prexit((signal, [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.

exit | beforeExit | uncaughtException | unhandledRejection | 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 are settled 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 */ )

Readme

Keywords

none

Package Sidebar

Install

npm i prexit

Weekly Downloads

1,934

Version

2.2.0

License

WTFPL

Unpacked Size

6.17 kB

Total Files

6

Last publish

Collaborators

  • porsager