Performance: Creating worker threads
This concept affects how CPU-intensive tasks impact the main thread and overall responsiveness of a Node.js application.
Jump into concepts and practice - no test required
import { Worker } from 'node:worker_threads'; const worker = new Worker(` const { parentPort } = require('worker_threads'); for (let i = 0; i < 1e9; i++) {} parentPort.postMessage('done'); `, { eval: true }); worker.on('message', msg => console.log(msg));
const heavyTask = () => {
// CPU-intensive loop
for (let i = 0; i < 1e9; i++) {}
};
heavyTask();| Pattern | CPU Usage | Main Thread Blocking | Responsiveness | Verdict |
|---|---|---|---|---|
| Synchronous heavy task on main thread | High CPU on main thread | Blocks main thread fully | Poor input responsiveness | [X] Bad |
| Heavy task in worker thread | High CPU but off main thread | Main thread free | Good input responsiveness | [OK] Good |
worker_threads in Node.js?worker_threads module?const { Worker } = require('worker_threads');const { Worker, isMainThread, parentPort } = require('worker_threads');
if (isMainThread) {
const worker = new Worker(__filename);
worker.on('message', msg => console.log('From worker:', msg));
worker.postMessage('Hello');
} else {
parentPort.on('message', msg => {
parentPort.postMessage(msg + ' World');
});
}const { Worker } = require('worker_threads');
const worker = new Worker('worker.js');
worker.on('message', msg => console.log(msg));
worker.postMessage('Start');new Worker('./calc.js') and using worker.on('message') plus worker.postMessage() is the standard pattern.new Worker() without arguments and call worker.send() to communicate is invalid because Worker requires a filename or code. Use require('worker_threads').run() to start the worker and get a promise is incorrect; no run() method exists. Create a child process with child_process.fork() and communicate with worker.postMessage() uses child_process, not worker_threads, and postMessage is not valid on child processes.