市场夺宝奇兵
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 lines
2.4 KiB

  1. # signal-exit
  2. When you want to fire an event no matter how a process exits:
  3. - reaching the end of execution.
  4. - explicitly having `process.exit(code)` called.
  5. - having `process.kill(pid, sig)` called.
  6. - receiving a fatal signal from outside the process
  7. Use `signal-exit`.
  8. ```js
  9. // Hybrid module, either works
  10. import { onExit } from 'signal-exit'
  11. // or:
  12. // const { onExit } = require('signal-exit')
  13. onExit((code, signal) => {
  14. console.log('process exited!', code, signal)
  15. })
  16. ```
  17. ## API
  18. `remove = onExit((code, signal) => {}, options)`
  19. The return value of the function is a function that will remove
  20. the handler.
  21. Note that the function _only_ fires for signals if the signal
  22. would cause the process to exit. That is, there are no other
  23. listeners, and it is a fatal signal.
  24. If the global `process` object is not suitable for this purpose
  25. (ie, it's unset, or doesn't have an `emit` method, etc.) then the
  26. `onExit` function is a no-op that returns a no-op `remove` method.
  27. ### Options
  28. - `alwaysLast`: Run this handler after any other signal or exit
  29. handlers. This causes `process.emit` to be monkeypatched.
  30. ### Capturing Signal Exits
  31. If the handler returns an exact boolean `true`, and the exit is a
  32. due to signal, then the signal will be considered handled, and
  33. will _not_ trigger a synthetic `process.kill(process.pid,
  34. signal)` after firing the `onExit` handlers.
  35. In this case, it your responsibility as the caller to exit with a
  36. signal (for example, by calling `process.kill()`) if you wish to
  37. preserve the same exit status that would otherwise have occurred.
  38. If you do not, then the process will likely exit gracefully with
  39. status 0 at some point, assuming that no other terminating signal
  40. or other exit trigger occurs.
  41. Prior to calling handlers, the `onExit` machinery is unloaded, so
  42. any subsequent exits or signals will not be handled, even if the
  43. signal is captured and the exit is thus prevented.
  44. Note that numeric code exits may indicate that the process is
  45. already committed to exiting, for example due to a fatal
  46. exception or unhandled promise rejection, and so there is no way to
  47. prevent it safely.
  48. ### Browser Fallback
  49. The `'signal-exit/browser'` module is the same fallback shim that
  50. just doesn't do anything, but presents the same function
  51. interface.
  52. Patches welcome to add something that hooks onto
  53. `window.onbeforeunload` or similar, but it might just not be a
  54. thing that makes sense there.