How to use worker threads in Node.js
Worker threads enable parallel execution of CPU-intensive tasks in Node.js without blocking the main event loop, crucial for computationally heavy operations. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented worker threads in Node.js applications throughout my 11 years of backend development. The most effective approach is using the built-in worker_threads module to offload intensive computations to separate threads. This method maintains application responsiveness while processing complex calculations or data transformations.
Use the worker_threads module to create workers for CPU-intensive tasks.
const { Worker } = require('worker_threads')
const runWorker = (data) => {
return new Promise((resolve, reject) => {
const worker = new Worker('./worker.js', {
workerData: data
})
worker.on('message', resolve)
worker.on('error', reject)
worker.on('exit', (code) => {
if (code !== 0) {
reject(new Error(`Worker stopped with exit code ${code}`))
}
})
})
}
runWorker({ numbers: [1, 2, 3, 4, 5] })
.then(result => console.log('Result:', result))
Here a new Worker is created pointing to a worker script file. The workerData option passes data to the worker thread. Event listeners handle the worker’s response message, errors, and exit events. The worker runs in a separate thread, allowing the main thread to remain responsive while processing completes.
Best Practice Note:
This is the approach we use in CoreUI backend services for image processing and data transformation tasks. Create a worker pool for recurring tasks to avoid thread creation overhead, limit concurrent workers based on CPU cores, and use worker threads for CPU-bound tasks only—use async operations for I/O-bound tasks.



