0
0
Node.jsframework~20 mins

Creating worker threads in Node.js - Practice Exercises

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Worker Threads Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a simple worker thread example
What will be printed to the console when this Node.js code runs?
Node.js
import { Worker, isMainThread, parentPort } from 'worker_threads';

if (isMainThread) {
  const worker = new Worker(new URL(import.meta.url));
  worker.on('message', (msg) => console.log(msg));
} else {
  parentPort.postMessage('Hello from worker');
}
Aundefined
BHello from worker
CError: Cannot find module
DNo output
Attempts:
2 left
💡 Hint
Remember that the worker sends a message back to the main thread.
component_behavior
intermediate
2:00remaining
Behavior of worker thread with data passed
What will be the output of this code snippet?
Node.js
import { Worker, isMainThread, parentPort, workerData } from 'worker_threads';

if (isMainThread) {
  const worker = new Worker(new URL(import.meta.url), { workerData: 5 });
  worker.on('message', (msg) => console.log(msg));
} else {
  parentPort.postMessage(workerData * 2);
}
A5
BNaN
C10
Dundefined
Attempts:
2 left
💡 Hint
Check how workerData is used inside the worker thread.
📝 Syntax
advanced
2:00remaining
Identify the syntax error in worker thread creation
Which option contains a syntax error that prevents the worker from starting?
Node.js
import { Worker, isMainThread } from 'worker_threads';

if (isMainThread) {
  const worker = new Worker('worker.js');
}
Aconst worker = new Worker(new URL('worker.js'));
Bconst worker = new Worker(new URL('worker.js', import.meta.url));
Cconst worker = new Worker(new URL(import.meta.url));
Dconst worker = new Worker('worker.js');
Attempts:
2 left
💡 Hint
Check how new URL() is used with relative paths in ES modules.
🔧 Debug
advanced
2:00remaining
Why does this worker thread code throw an error?
This code throws an error when run. What is the cause?
Node.js
import { Worker, isMainThread } from 'worker_threads';

if (isMainThread) {
  const worker = new Worker('./worker.js');
  worker.on('message', (msg) => console.log(msg));
} else {
  parentPort.postMessage('Hi');
}
ACannot use relative path string without URL in ES modules
BparentPort is undefined in main thread
CMissing import of parentPort in worker thread
DWorker file './worker.js' does not exist
Attempts:
2 left
💡 Hint
Consider how worker threads are created in ES modules with relative paths.
lifecycle
expert
3:00remaining
Order of events in worker thread lifecycle
What is the correct order of these events when a worker thread is created and communicates back?
A1,3,2,4
B2,1,3,4
C3,1,2,4
D1,2,3,4
Attempts:
2 left
💡 Hint
Think about what happens first: creation, running, messaging, then receiving.