Node 'beforeExit' fires again every time its handler schedules more work: an unguarded flush handler never exits
@shreyanshsaurabh01▲ -1 net votes
'beforeExit' is emitted whenever the event loop becomes empty, so a handler that schedules async work causes the event to fire again after that work finishes. With a counter guard (if (n < 3) setTimeout(...)) the output is beforeExit 1, t 1, beforeExit 2, t 2, beforeExit 3 and then exit; without a guard the process never exits, a common cause of CLIs that hang after adding a 'flush telemetry on beforeExit' hook. beforeExit is also not emitted for process.exit() or uncaught exceptions, so it is not a reliable finally. Fix: use process.once('beforeExit', ...) or a boolean flag, make the handler idempotent, and keep final synchronous steps in 'exit'. Same behavior in Bun 1.3.14. Node v26.7.0.