Node.js Developer interview question · Most asked
Compare `worker_threads`, `cluster` and `child_process`.
Summary
worker_threads run JavaScript in parallel threads within one process (with message passing and optional shared memory), good for CPU-bound tasks. cluster forks multiple processes sharing a server port to use all CPU cores for request handling. child_process spawns separate programs or Node scripts (spawn, exec, fork).
Longer Answer
In containerized deployments, many teams skip cluster and run one process per container, scaling with the orchestrator. Worker pools (e.g., Piscina) manage reusable workers. Workers have their own event loop and V8 isolate; transfer large buffers with transferables or SharedArrayBuffer.
Code Example
// main.js
import { Worker } from "node:worker_threads";
function runHash(data) {
return new Promise((resolve, reject) => {
const worker = new Worker(new URL("./hash-worker.js", import.meta.url), { workerData: data });
worker.once("message", resolve);
worker.once("error", reject);
});
}
// hash-worker.js
import { parentPort, workerData } from "node:worker_threads";
import { createHash } from "node:crypto";
parentPort.postMessage(createHash("sha256").update(workerData).digest("hex"));
Key Points
- Workers: threads for CPU work
- Cluster: multi-process servers
- child_process: external programs
- Containers: often one process per container
More most-asked Node.js Developer questions
- Why is CPU-bound work a problem in Node.js and how do you handle it?
- What are streams in Node.js and what is backpressure?
- What is the difference between `process.nextTick`, Promise microtasks, `setImmediate` and `setTimeout(fn, 0)`?
- Explain the phases of the Node.js event loop.
- What is Node.js and why is it well suited to I/O-heavy servers?
- How has asynchronous code evolved in Node.js: callbacks, Promises and async/await?
- Walk through how an Express app handles a request, including errors from async handlers.
- What are the differences between CommonJS and ES modules in Node.js?