Worker Lifecycle: Exit and Error Events
You'll learn how to gracefully handle worker termination and catch errors to build robust concurrent applications.
Why This Matters
When you spawn a worker thread in Node.js, it doesn't just run forever—it completes its task and exits, or it might crash with an error. Without handling these lifecycle events, your application won't know when workers finish or fail, leading to hung processes, resource leaks, or silent failures.
The exit Event
The exit event fires when a worker thread terminates, either because its code finished executing or because it was explicitly stopped. You attach a listener to the worker instance:
const { Worker } = require('worker_threads');
const worker = new Worker('./my-worker.js');
worker.on('exit', (exitCode) => {
if (exitCode === 0) {
console.log('Worker completed successfully');
} else {
console.log(`Worker stopped with exit code ${exitCode}`);
}
});
The exitCode tells you how it exited: 0 means success, while non-zero values indicate errors or forced termination.
The error Event
The error event catches uncaught exceptions thrown inside the worker before it crashes:
worker.on('error', (err) => {
console.error('Worker error:', err.message);
// Decide whether to restart the worker, log the error, etc.
});
Without this listener, an unhandled error in a worker will crash your main Node.js process.
Together They Cover Worker Failure
Think of these events like emergency exits: error catches the fire alarm, while exit confirms everyone left the building. Always handle both to know why and when workers stop running.
Key Takeaway: Use the exit event to detect when workers finish (with an exit code), and the error event to catch uncaught exceptions—both are essential for stable multi-threaded applications.