Node.js › Clustering & Worker Threads
What is the WorkerData option when creating a Worker, and how does it differ from communicating via postMessage() after creation?
AdvancedAnswer
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.