Worker threads and messages
Prerequisites: previous curriculum lessons on Node streams, HTTP, buffers and asynchronous errors. Local lab baseline: Node.js 22.16.0, Linux, ESM. Use a disposable directory. Static examples are not ByteMind interactive execution. Each example is independent; save the named files together and run node main.mjs. The author harness imposes a five-second process deadline.
How it works
Create a Worker with a reviewed module file, provide initial data using workerData, and communicate with postMessage and parentPort. Messages normally use structured cloning, which copies supported values but not arbitrary functions. Treat the worker protocol as an explicit input/result contract and handle error and exit as well as messages. A worker shares process privileges, so it is not a security sandbox. Prefer fixed worker files, bounded input and a finite worker count. Measure before claiming a speed improvement.
Calculate a sum in a reviewed worker module
import {Worker} from 'node:worker_threads';import {once} from 'node:events';const worker=new Worker(new URL('./worker.mjs',import.meta.url),{workerData:[2,3,4],resourceLimits:{maxOldGenerationSizeMb:32}});const exit=once(worker,'exit');try {const [result]=await once(worker,'message');console.log(result);console.log('exit', (await exit)[0]);}finally{await worker.terminate();}import {parentPort,workerData} from 'node:worker_threads';if(!Array.isArray(workerData)||workerData.length>100||!workerData.every(n=>Number.isInteger(n)&&Math.abs(n)<=100))throw new Error('invalid input');parentPort.postMessage(workerData.reduce((sum,n)=>sum+n*n,0));Expected output:
29exit 0The worker computes the sum of squares; the parent checks both result and process-local worker exit.
Observe a worker error and exit
import {Worker} from 'node:worker_threads';const worker=new Worker(new URL('./worker.mjs',import.meta.url));const finished=new Promise(resolve=>worker.once('exit',resolve));worker.once('error',error=>console.log(error.message));try {console.log('exit',await finished);}finally{await worker.terminate();}Expected output:
invalid taskexit 1An uncaught worker exception is reported to the parent and terminates the worker. The parent records both events.
Common mistakes
Do not create unlimited workers for every request or send executable user text to workers. An exception in a worker must be handled; receiving a message does not alone establish clean exit.
Practice
Change the input array to an empty list and predict the result. Add a test for a value outside the worker input contract.
Further reading
Official documentation: worker_threads. Internal reference candidate: node-worker-threads-and-messages-lookup (route not verified).
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Worker threads and messages — knowledge check
Apply the lesson to a fresh scenario and explain the resource or protocol boundary.
Which workload is a reasonable worker candidate?
What does a worker error handler provide?
Why benchmark before adopting workers?