0
0
Node.jsframework~30 mins

Worker thread vs child process in Node.js - Hands-On Comparison

Choose your learning style9 modes available
Worker Thread vs Child Process in Node.js
📖 Scenario: You are building a Node.js application that needs to perform heavy calculations without blocking the main program. You want to learn how to use worker_threads and child_process modules to run tasks in parallel.
🎯 Goal: Create a simple Node.js app that uses a worker thread and a child process to run the same calculation separately. You will see how to set up both and send messages between the main program and these parallel workers.
📋 What You'll Learn
Create a worker thread using the worker_threads module
Create a child process using the child_process module
Send a number from the main thread to both the worker thread and child process
Receive the squared result back from both and log it
Use exact variable and function names as instructed
💡 Why This Matters
🌍 Real World
Node.js apps often need to run heavy tasks without freezing the main program. Worker threads and child processes help by running code in parallel.
💼 Career
Understanding these parallel processing methods is important for backend developers to build efficient, responsive Node.js applications.
Progress0 / 4 steps
1
Set up the main data and imports
Create a variable called number and set it to 7. Import Worker from worker_threads and fork from child_process.
Node.js
Need a hint?

Use const number = 7; and import Worker and fork exactly as shown.

2
Create a worker thread to calculate square
Create a new Worker instance called worker that runs a file named 'worker.js'. This worker will receive the number and calculate its square.
Node.js
Need a hint?

Use new Worker('./worker.js') to create the worker thread.

3
Create a child process to calculate square
Create a child process called child using fork to run a file named 'child.js'. This child process will also receive the number and calculate its square.
Node.js
Need a hint?

Use fork('./child.js') to create the child process.

4
Send number and receive results from worker and child
Send the number to both worker and child. Listen for messages from both using worker.on('message', ...) and child.on('message', ...). Log the results with console.log using the exact text: "Worker result: " and "Child result: " followed by the squared number.
Node.js
Need a hint?

Use postMessage and send to send data. Use on('message') to receive and console.log to print results.