NODEJS Contents

Worker Threads

Worker threads enable CPU-bound parallelism inside a single process; use them for hashing, compression, parsing, and heavy computations.

On this page

Why Worker Threads Matter

CPU-bound tasks block the event loop. Worker threads run JavaScript in separate threads, allowing parallel computation without blocking request handling.

When to Use Them

  • Password hashing with high cost factors
  • Image processing
  • Large JSON transformations
  • Data compression or encryption

Basic Example

import { Worker } from 'node:worker_threads';

const worker = new Worker('./worker.js');
worker.postMessage({ job: 'compute' });

worker.on('message', result => {
  console.log(result);
});

Communication Cost

Data passed between threads is copied or transferred. Large objects increase overhead. Design message payloads carefully.

Production Guidance

Measure the benefit before introducing worker threads. They increase complexity and should be used only for true CPU bottlenecks.