index.js 1006 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. 'use strict';
  2. const callbacks = new Set();
  3. let isCalled = false;
  4. let isRegistered = false;
  5. function exit(exit, signal) {
  6. if (isCalled) {
  7. return;
  8. }
  9. isCalled = true;
  10. for (const callback of callbacks) {
  11. callback();
  12. }
  13. if (exit === true) {
  14. process.exit(128 + signal); // eslint-disable-line unicorn/no-process-exit
  15. }
  16. }
  17. module.exports = callback => {
  18. callbacks.add(callback);
  19. if (!isRegistered) {
  20. isRegistered = true;
  21. process.once('exit', exit);
  22. process.once('SIGINT', exit.bind(null, true, 2));
  23. process.once('SIGTERM', exit.bind(null, true, 15));
  24. // PM2 Cluster shutdown message. Caught to support async handlers with pm2, needed because
  25. // explicitly calling process.exit() doesn't trigger the beforeExit event, and the exit
  26. // event cannot support async handlers, since the event loop is never called after it.
  27. process.on('message', message => {
  28. if (message === 'shutdown') {
  29. exit(true, -128);
  30. }
  31. });
  32. }
  33. return () => {
  34. callbacks.delete(callback);
  35. };
  36. };