skip to content

In Node.js, when is the process 'beforeExit' event emitted versus 'exit', and why can only 'beforeExit' do asynchronous work?

level: middleimportance: should knowfreq 40%

answer

  1. one fires when the loop drains
  2. one fires when exit is certain
  3. explicit exit skips one of them
  4. work queued in 'exit' is abandoned

basics

~20 s

'beforeExit' fires when the event loop has drained and Node is about to exit naturally; a listener may schedule async work, which keeps the process running. 'exit' fires once exit is certain, such as after process.exit(), and its listeners must be synchronous.

solid answer

~40 s

`'beforeExit'` is emitted when Node empties its event loop and has nothing left to schedule. The listener receives `process.exitCode`, and if it starts asynchronous work, such as a timer or a write, the loop runs again and the event fires again the next time it drains. It is not emitted for explicit termination: `process.exit()` and an uncaught exception skip it. `'exit'` is emitted when the process is about to exit: after `process.exit()`, when the loop has no more work, and, in Node's fatal-exception path, just before an uncaught-exception crash with code 1. At that point exit cannot be prevented: Node terminates as soon as the `'exit'` listeners return, so anything they queue is abandoned. So `'beforeExit'` suits a final asynchronous flush in a script that ends naturally, and `'exit'` only synchronous last words.

code

javascript · 14 lines
javascript
// flush.cjs
let flushed = false;
const buffer = ['job 1 done', 'job 2 done'];

process.on('beforeExit', (code) => {
  if (flushed) return; // without this guard the loop never ends
  flushed = true;
  setTimeout(() => console.log(`flushed ${buffer.length} lines (code ${code})`), 50);
});

process.on('exit', (code) => {
  console.log(`exit ${code}`);
  setTimeout(() => console.log('never printed'), 0);
});

go deeper

for a junior

Recall the two triggers: 'beforeExit' when the loop drains, 'exit' when the process is about to end, and that 'exit' listeners must be synchronous.

for a middle

Explain the order of a natural exit, why scheduling work in 'beforeExit' keeps the process alive, and which explicit terminations skip it.

for a senior

Diagnose the classic bugs: an async write lost in 'exit', a process that never ends because 'beforeExit' keeps scheduling, and shutdown code that never runs in a server.

for a principal

Set the house rule that neither event is a service shutdown hook, and that the last synchronous moment is reserved for small, local, best-effort bookkeeping.

## Two events, two moments A Node.js process normally exits when its **event loop** has no pending work: no timers, no open sockets or servers, no queued I/O. Around that moment the `process` object emits two different events, and they are easy to confuse. | | `'beforeExit'` | `'exit'` | |---|---|---| | When it fires | The loop has drained and Node has nothing left to schedule | The process is about to terminate | | On `process.exit()` | Not emitted | Emitted | | On an uncaught exception crash | Not emitted | Emitted with code 1 by the fatal-exception path | | Listener argument | `process.exitCode` | The exit code being used | | Asynchronous work | Allowed, and it keeps the process alive | Abandoned when listeners return | | Can it prevent exit? | Yes, by scheduling work | No | The documented triggers for `'exit'` are an explicit `process.exit()` and an event loop with no more work; Node's own fatal-exception handler also emits it, with code 1, before an unhandled crash. ## The order of a natural exit When a script simply runs out of work, Node goes through these steps: 1. The last callback finishes and the loop finds nothing pending. 2. Node emits `'beforeExit'` with `process.exitCode`, which the docs' own example shows as 0 when nothing set it. 3. If a listener scheduled new work, the loop runs that work and Node goes back to step 2 when it drains again. 4. If nothing new was scheduled, Node emits `'exit'` with the final code. 5. As soon as the `'exit'` listeners return, the process terminates. The Node docs say it directly: listeners of `'exit'` **must only perform synchronous operations**, because any additional work still queued in the event loop is abandoned. Their example schedules a `setTimeout` inside an `'exit'` listener, and its callback never runs. ## A worked trace Consider a script with two listeners: a guarded `'beforeExit'` listener that starts one 50 ms timer, and an `'exit'` listener that logs a line and then calls `setTimeout`. It shows both rules at once. The script has no pending work after its top level runs, so the loop drains and `'beforeExit'` fires with code 0. The listener sets its guard and starts a 50 ms timer, which refills the loop. The timer prints its line, the loop drains again, `'beforeExit'` fires a second time and the guard returns without scheduling anything. Now `'exit'` fires: its `console.log` runs because it is synchronous, while the `setTimeout` it schedules is abandoned and `'never printed'` never appears. ## Traps - **A `'beforeExit'` listener that always schedules work never lets the process exit.** Each new timer refills the loop, the loop drains, the event fires again, and the cycle repeats. Guard it with a flag so the asynchronous flush runs once. - **`'beforeExit'` does not fire in a server.** A listening HTTP server keeps the loop alive, so the loop never drains while it runs. When such a process ends through `process.exit()` or a crash, `'beforeExit'` is skipped by design. - **Awaiting in `'exit'` silently does nothing.** An `async` listener starts its first `await` and returns a promise; Node terminates without waiting for it, so a final write to a database or a remote logger never happens. - **`'exit'` is not a signal hook.** Its documented triggers are `process.exit()` and an empty loop. `SIGKILL` cannot be intercepted at all, and handling `SIGTERM` belongs to the material on draining before exit. - **Docs do not promise `'beforeExit'` as a general replacement for `'exit'`.** They say it should not be used that way unless the intention is to schedule additional work. ## What belongs in each listener Put in `'beforeExit'`: - a final asynchronous flush of a buffered metrics or log batch in a command-line tool or batch job; - a last check that schedules one more unit of work before a script ends. Put in `'exit'`: - synchronous bookkeeping, such as `fs.writeFileSync` of a small state file or `fs.writeSync` of a final line; - nothing that returns a promise, opens a socket or starts a timer. For a long-running service, neither event is a shutdown hook. A server is stopped by signal handling and draining, and a crash is handled through the crash events; `'exit'` remains the last synchronous moment in both cases.

  • Why does a 'beforeExit' listener never run in a Node.js HTTP server that is shut down with process.exit()?
    While the server listens, its handle keeps the event loop alive, so the loop never drains and `'beforeExit'` has no moment to fire. `process.exit()` is explicit termination, which skips `'beforeExit'` entirely and goes straight to the `'exit'` listeners. Shutdown logic for a server therefore belongs in signal handling, not in `'beforeExit'`.
  • Is 'exit' emitted when a Node.js process crashes on an uncaught exception?
    Yes. With no `'uncaughtException'` listener, Node's fatal-exception path sets the exit code to 1 and emits `'exit'` with 1 before terminating. The same rule applies there: only synchronous work in the listener completes. `'beforeExit'` is not emitted for that crash.

'beforeExit' is last call at a bar: anyone may still order another round, and the bar stays open while it is served. 'exit' is the lights coming on: you can say goodbye, but no new order will be served. Being thrown out by the police, like process.exit(), skips last call entirely.

  • An 'exit' listener can await a final database write before the process ends.
  • 'beforeExit' runs when you call process.exit().
  • 'beforeExit' is the right place for shutdown logic in an HTTP server.
  • A setTimeout in an 'exit' listener delays termination until it fires.
  • 'beforeExit' fires exactly once, whatever its listener does.