exit Hook Flushes Pending Writes
Register a process exit handler that synchronously flushes pending writes, because async work started inside exit handlers cannot finish.
Code
// Buffered audit entries that a real app would persist somewhere
const pendingWrites = ['login:u1', 'order:42', 'logout:u1'];
// The exit hook runs once, synchronously, right before shutdown.
// Anything async started inside it will never finish, so only
// synchronous flushes belong here.
process.on('exit', (code) => {
console.log(`exit hook: flushing ${pendingWrites.length} entries`);
for (const entry of pendingWrites) {
console.log(`flushed: ${entry}`);
}
console.log(`exit hook done, code ${code}`);
});
process.on('exit', () => {
// Timers queued here would never fire: the loop stops after
// the exit handlers return
console.log('no async work possible inside exit hooks');
});
console.log('app work finished, waiting for the loop to drain');Output
Captured from a sandboxed run of this snippet in the build pipeline.
app work finished, waiting for the loop to drain
exit hook: flushing 3 entries
flushed: login:u1
flushed: order:42
flushed: logout:u1
exit hook done, code 0
no async work possible inside exit hooksWhy the flush must be synchronous
process.on('exit', ...) handlers run once, synchronously, right before shutdown; after they return, the event loop no longer services timers or I/O. That is why both handlers in the file only call console.log and loop over pendingWrites — the second handler’s comment (“Timers queued here would never fire”) marks that boundary. Any async work started inside would be abandoned mid-flight.
The exact shutdown output
The normal-work line prints first, then both exit handlers run in registration order:
app work finished, waiting for the loop to drain
exit hook: flushing 3 entries
flushed: login:u1
flushed: order:42
flushed: logout:u1
exit hook done, code 0
no async work possible inside exit hooks
exit hook: flushing 3 entries comes from pendingWrites.length; each flushed: line is one iteration of for (const entry of pendingWrites); code 0 is the handler’s exit-code argument; the final line proves the second registered handler also ran.
The line that drains the buffer
for (const entry of pendingWrites) {
console.log(`flushed: ${entry}`);
}
This loop is the “flush”: with synchronous writes it completes inside the handler, which is the only guarantee the exit event gives you.
Interactive Tools for This Topic
FAQ
- Are there dependencies to manage?
- No. There are no dependencies to declare or install. Its state lives in module-level bindings: `pendingWrites`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.