Intermediate LevelNode JS
How do Worker Threads (node:worker_threads) execute CPU-intensive tasks without blocking the main event loop?
❓ Interview Prompt: Explain `node:worker_threads`, isolated V8 instances, main thread offloading, parentPort IPC messaging, and Worker pools.
Because Node.js main thread executes single-threaded JavaScript, heavy CPU tasks (image processing, encryption, PDF generation) freeze the event loop for all incoming requests!
Worker Threads ('node:worker_threads'):
Spawns isolated V8 JS engines in separate OS threads with separate memory, communicating with the main thread via 'postMessage()'.
Code Implementation Example
javascript
// main.js
import { Worker } from 'node:worker_threads';
function runCpuWorker(data) {
return new Promise((resolve, reject) => {
const worker = new Worker('./worker-script.js', { workerData: data });
worker.on('message', resolve);
worker.on('error', reject);
});
}💡Offloading heavy tasks to Worker Threads.
🎯 Interview Key Takeaway
Use Worker Threads to run CPU-bound tasks in separate V8 instances without blocking the main event loop.
#Worker Threads#CPU-Bound#v8#Concurrency#Intermediate
Back to all Node JS Questions→