Challenge - 5 Problems
Worker Threads Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate2:00remaining
Why use worker threads in Node.js?
Which of the following best explains why worker threads are important in Node.js?
Attempts:
2 left
💡 Hint
Think about how Node.js handles tasks and what happens when a task takes a long time.
✗ Incorrect
Worker threads let Node.js run JavaScript code in parallel threads. This helps avoid blocking the main thread, which keeps the app responsive.
❓ component_behavior
intermediate2:00remaining
Output of worker thread example
What will be the output of this Node.js code using worker threads?
Node.js
const { Worker, isMainThread, parentPort } = require('worker_threads');
if (isMainThread) {
const worker = new Worker(__filename);
worker.on('message', message => console.log('From worker:', message));
console.log('Main thread running');
} else {
parentPort.postMessage('Hello from worker');
}Attempts:
2 left
💡 Hint
Consider the order of console.log calls in main and worker threads.
✗ Incorrect
The main thread logs first, then the worker sends a message back which is logged next.
🔧 Debug
advanced2:00remaining
Identify the error in worker thread usage
What error will this Node.js code produce?
Node.js
const { Worker } = require('worker_threads');
const worker = new Worker('console.log("Hello")');Attempts:
2 left
💡 Hint
Check what the Worker constructor expects as input.
✗ Incorrect
The Worker constructor requires a file path or URL, not a string of code.
❓ state_output
advanced2:00remaining
State sharing between main and worker threads
Given this code, what will be the final value of 'counter' in the main thread?
Node.js
const { Worker, isMainThread, parentPort, workerData } = require('worker_threads');
let counter = 0;
if (isMainThread) {
const worker = new Worker(__filename, { workerData: counter });
worker.on('message', value => {
counter = value;
console.log('Counter in main:', counter);
});
} else {
let localCounter = workerData;
localCounter += 5;
parentPort.postMessage(localCounter);
}Attempts:
2 left
💡 Hint
Remember that workerData is a copy, not shared memory.
✗ Incorrect
The worker receives a copy of counter (0), adds 5, and sends back 5. The main thread updates its counter to 5.
📝 Syntax
expert2:00remaining
Correct syntax to create a worker thread with inline code
Which option correctly creates a worker thread that runs inline JavaScript code in Node.js?
Attempts:
2 left
💡 Hint
Worker constructor accepts a file path, URL, or data URL with type module.
✗ Incorrect
Option A uses a data URL with type 'module' which is the correct way to run inline code in a worker thread.