🟢 Node.js Intermediate

What are Worker Threads in Node.js?

Why Interviewers Ask This

Mid-level Node.js roles require deep understanding of this topic. Interviewers ask this to separate candidates who truly understand the mechanics from those who only know surface-level concepts.

Answer

Worker Threads (introduced in Node.js 10, stable in 12) allow Node.js to execute JavaScript in parallel threads, sharing memory via SharedArrayBuffer. Unlike child_process which spawns separate processes with separate memory, Worker Threads run in the same process and can share data efficiently. Workers communicate with the main thread via postMessage() and on("message"). Use Worker Threads for CPU-intensive operations that would block the event loop: image processing, video encoding, complex calculations, ML inference, parsing large data. Example: const { Worker } = require("worker_threads"); const worker = new Worker("./task.js", { workerData: { input } }); worker.on("message", result => ...); worker.on("error", err => ...);. Do NOT use Worker Threads for I/O-bound tasks — Node.js's async I/O already handles those efficiently without threads. The thread pool (libuv) already handles some I/O operations in the background.

Common Mistake

Many candidates answer correctly but can't explain the 'why'. Always be prepared to justify your answer with a concrete example or use case from your Node.js experience.