Worker and parentPort message exchange
Worker threads run JavaScript in separate isolates inside one Node process. They are useful for bounded CPU-heavy calculations that would otherwise occupy the main JavaScript thread. Workers do not automatically improve ordinary asynchronous I/O, and startup and message copying have costs. 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. 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. Sources: https://nodejs.org/download/release/v22.16.0/docs/api/worker_threads.html.
Formal Syntax & Structure
new Worker(filename[, options]); worker.postMessage(value[, transferList])Working Example
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();}