Process Event: 'exit'
You'll learn how to run cleanup code synchronously right before your Node.js program terminates.
What Happens When a Process Exits
When your Node.js application is about to shut down—whether you called process.exit(), the event loop emptied naturally, or an uncaught error occurred—Node.js emits an 'exit' event. This gives you one final chance to perform cleanup tasks before the process terminates completely.
Listening for the Exit Event
You attach a listener to the 'exit' event just like any other event in Node.js:
process.on('exit', (code) => {
console.log('Process is about to exit with code:', code);
});
The callback receives the exit code as its parameter. By convention, 0 means success, while non-zero values indicate errors.
Critical Constraints
The 'exit' event handler has strict limitations:
- Only synchronous code is allowed—no async operations, Promises, or callbacks
- The event loop has already stopped, so timers and I/O won't work
- You cannot prevent the exit; the process will terminate
Think of it like a train leaving the station: you can shout a final goodbye, but you can't unpack your luggage or stop the train.
Practical Use Cases
process.on('exit', (code) => {
// Log final statistics (synchronously)
console.log('Total requests processed:', requestCount);
// Clean up synchronous resources
// Note: file writes here are risky!
});
This is ideal for final logging, closing synchronous resources, or reporting statistics—things that complete immediately.
Key Takeaway: The 'exit' event lets you run synchronous cleanup code right before your Node.js process terminates, but async operations won't work because the event loop has already stopped.