typescriptadvanced
Node.js Worker Threads for Parallel Processing
Use Worker Threads to run CPU-intensive tasks in parallel without blocking the event loop.
typescriptPress ⌘/Ctrl + Shift + C to copy
import { Worker, isMainThread, parentPort, workerData } from 'node:worker_threads';
import { cpus } from 'node:os';
if (isMainThread) {
// Main thread: distribute work across workers
async function processInParallel<T, R>(
items: T[],
workerFile: string
): Promise<R[]> {
const numWorkers = Math.min(cpus().length, items.length);
const chunkSize = Math.ceil(items.length / numWorkers);
const promises = Array.from({ length: numWorkers }, (_, i) => {
const chunk = items.slice(i * chunkSize, (i + 1) * chunkSize);
return new Promise<R[]>((resolve, reject) => {
const worker = new Worker(workerFile, { workerData: chunk });
worker.on('message', resolve);
worker.on('error', reject);
});
});
const results = await Promise.all(promises);
return results.flat();
}
// Usage
const data = Array.from({ length: 1000 }, (_, i) => i);
const results = await processInParallel(data, new URL(import.meta.url).pathname);
console.log(`Processed ${results.length} items`);
} else {
// Worker thread: process assigned chunk
const chunk = workerData as number[];
const results = chunk.map((n) => {
// CPU-intensive work
let sum = 0;
for (let i = 0; i < 1_000_000; i++) sum += Math.sqrt(n + i);
return { input: n, result: sum };
});
parentPort?.postMessage(results);
}Use Cases
- CPU-intensive data processing without blocking
- Parallel image or file processing
- Splitting heavy computation across CPU cores
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptadvanced
Node.js Cluster Mode for Scaling
Scale Node.js across CPU cores using the cluster module with automatic worker respawning.
Best for: Utilizing all CPU cores for HTTP servers
#nodejs#cluster
typescriptadvanced
Performance Measurement
Measure execution time with performance.now(), Performance API marks, measures, and PerformanceObserver.
Best for: Function execution profiling
#nodejs#performance
typescriptadvanced
HTTP/2 Server with Stream Push
Create an HTTP/2 server with server push, multiplexed streams, and TLS configuration in Node.js.
Best for: High-performance web servers
#nodejs#http2
typescriptintermediate
In-Memory Caching with LRU Strategy
Implement LRU cache with TTL expiration, size limits, and cache-aside pattern for Node.js applications.
Best for: API response caching
#nodejs#caching