isMainThread and workerData
You'll learn how to detect execution context and pass initialization data to workers.
When working with Node.js worker threads, you often need to write code that behaves differently depending on whether it's running in the main thread or inside a worker. The isMainThread boolean from the worker_threads module tells you exactly where your code is executing. Meanwhile, workerData lets you pass initial configuration or input to a worker when you create it.
Checking isMainThread
The isMainThread property is true when your code runs in the main Node.js process and false when it runs inside a worker. This lets you write a single file that contains both the main thread logic and the worker logic:
const { isMainThread, Worker, workerData } = require('worker_threads');
if (isMainThread) {
// Main thread: create and manage workers
console.log('Running in main thread');
const worker = new Worker(__filename);
} else {
// Worker thread: do the actual work
console.log('Running in worker thread');
}
Passing workerData
When creating a Worker, you can pass an options object with a workerData property. This data becomes available inside the worker via the workerData import:
if (isMainThread) {
const worker = new Worker(__filename, {
workerData: { task: 'calculate', value: 42 }
});
} else {
console.log('Worker received:', workerData);
// Output: Worker received: { task: 'calculate', value: 42 }
// Use the data to configure worker behavior
if (workerData.task === 'calculate') {
const result = workerData.value * 2;
console.log('Result:', result);
}
}
The workerData is cloned (structured clone), so it's separate from the original object—changes in the worker won't affect the main thread's version.
Key Takeaway: Use isMainThread to branch logic between main and worker contexts, and pass initial configuration to workers via the workerData option for flexible, self-contained worker scripts.