Passing data to workers in Node.js
📖 Scenario: You are building a Node.js application that needs to perform a heavy calculation without blocking the main program. To do this, you will use a worker thread and pass data to it.
🎯 Goal: Create a worker thread in Node.js and pass a number to it. The worker will calculate the square of the number and send the result back.
📋 What You'll Learn
Create a worker thread using the
worker_threads modulePass a number to the worker using
workerDataIn the worker, calculate the square of the number
Send the result back to the main thread using
parentPort.postMessageReceive the result in the main thread and handle it
💡 Why This Matters
🌍 Real World
Using worker threads helps Node.js applications perform heavy tasks without freezing the user interface or main process.
💼 Career
Understanding how to pass data to workers and handle their responses is important for building efficient, scalable Node.js applications.
Progress0 / 4 steps