0
0
Node.jsframework~5 mins

Passing data to workers in Node.js

Choose your learning style9 modes available
Introduction

Workers let your program do many things at once. Passing data to workers helps them know what to do.

When you want to run heavy tasks without stopping the main program.
When you need to send information to a worker to start its job.
When you want to split work into smaller parts and share data with each part.
When you want to keep your app fast by doing work in the background.
Syntax
Node.js
const { Worker } = require('worker_threads');

const worker = new Worker('./worker.js', { workerData: yourData });

workerData is the key to send data to the worker.

The data can be any value that can be cloned, like numbers, strings, objects.

Examples
Sends an object with a name to the worker.
Node.js
const { Worker } = require('worker_threads');

const worker = new Worker('./worker.js', { workerData: { name: 'Alice' } });
Sends a number to the worker.
Node.js
const { Worker } = require('worker_threads');

const worker = new Worker('./worker.js', { workerData: 42 });
Sends an array of strings to the worker.
Node.js
const { Worker } = require('worker_threads');

const worker = new Worker('./worker.js', { workerData: ['apple', 'banana'] });
Sample Program

This example shows how to send data to a worker. The main file sends a task and a limit number. The worker adds numbers from 1 to the limit and sends back the result.

Node.js
/* main.js */
const { Worker } = require('worker_threads');

const worker = new Worker('./worker.js', { workerData: { task: 'count', limit: 5 } });

worker.on('message', (msg) => {
  console.log('Message from worker:', msg);
});

worker.on('error', (err) => {
  console.error('Worker error:', err);
});

worker.on('exit', (code) => {
  console.log('Worker stopped with exit code', code);
});

/* worker.js */
const { parentPort, workerData } = require('worker_threads');

if (workerData.task === 'count') {
  let count = 0;
  for (let i = 1; i <= workerData.limit; i++) {
    count += i;
  }
  parentPort.postMessage(`Sum from 1 to ${workerData.limit} is ${count}`);
} else {
  parentPort.postMessage('Unknown task');
}
OutputSuccess
Important Notes

Data sent with workerData is read-only inside the worker.

Use parentPort.postMessage() to send messages back to the main thread.

Workers run in separate threads, so data is cloned, not shared directly.

Summary

Workers get data through the workerData option when created.

This data tells the worker what to do or what information to use.

Workers send results back using messages with parentPort.postMessage().