What is the WorkerData option when creating a Worker, and how does it differ from communicating via postMessage() after creation?
Short answer
workerData is a value passed once, synchronously, at Worker construction time, immediately available inside the worker without waiting for an initial message -- useful for initial configuration, whereas postMessage() is used for ongoing communication after the worker is already…
Advertisement
AModel answer
workerData is a value passed once, synchronously, at Worker construction time, immediately available inside the worker without waiting for an initial message -- useful for initial configuration, whereas postMessage() is used for ongoing communication after the worker is already running.
if (isMainThread) {
const worker = new Worker(__filename, { workerData: { inputFile: 'data.csv' } });
} else {
console.log('Processing:', workerData.inputFile);
}Real-world example
A batch-processing worker receives its input file path via workerData at creation, needing no initial handshake before beginning work, while using postMessage() afterward for progress updates.
Likely follow-ups
- Why can't workerData be used for ongoing communication after the worker has started?
- What happens if workerData contains a value that can't be structured-cloned, like a function?
Related topics