Node.js › Clustering & Worker Threads
How do you gracefully terminate a worker thread, and what's the difference between worker.terminate() and letting it exit naturally?
IntermediateAnswer
worker.terminate() forcibly and immediately stops execution regardless of current work, abandoning in-progress work -- appropriate for canceling unneeded tasks. Letting a worker exit naturally allows pending operations to complete first, providing a cleaner shutdown when its own work is genuinely finished.
setTimeout(() => worker.terminate(), 30000); // cancel if it takes too long
worker.on('exit', (code) => console.log(`Worker exited with code ${code}`));Real-world example A request-timeout mechanism calls worker.terminate() on a task running over 30 seconds, ensuring a stuck task doesn't tie up pool capacity indefinitely, at the cost of losing partial progress.