Consider this Node.js code using worker threads. What will be printed to the console?
import { Worker, isMainThread, parentPort } from 'worker_threads'; if (isMainThread) { const worker = new Worker(new URL(import.meta.url)); worker.on('message', (msg) => console.log('Received:', msg)); worker.postMessage('start'); } else { parentPort.on('message', (msg) => { if (msg === 'start') { parentPort.postMessage('done'); } }); }
Think about how the worker listens and sends messages back to the main thread.
The main thread sends 'start' to the worker. The worker listens for 'start' and replies with 'done'. The main thread logs 'Received: done'.
In this Node.js code, what will be the value of result after the worker sends its message?
import { Worker, isMainThread, parentPort } from 'worker_threads'; let result = null; if (isMainThread) { const worker = new Worker(new URL(import.meta.url)); worker.on('message', (msg) => { result = msg; }); worker.postMessage('compute'); setTimeout(() => { console.log('Result:', result); }, 100); } else { parentPort.on('message', (msg) => { if (msg === 'compute') { parentPort.postMessage(42); } }); }
The message event updates result before the timeout logs it.
The worker sends 42 back. The main thread sets result = 42. After 100ms, result is 42 and logged.
Which of these code snippets will cause a syntax error when used inside a Node.js worker thread?
Check the syntax of the if statement in each option.
Option D misses parentheses around the if condition, causing a syntax error.
Given this worker code snippet, why does it throw a TypeError?
import { parentPort } from 'worker_threads'; parentPort.postMessage('hello');
Check where the code is executed: main thread or worker thread?
parentPort is only defined inside worker threads. If this code runs in the main thread, parentPort is null, causing the error.
You spawn multiple worker threads in Node.js to perform tasks. How do you correctly receive and aggregate their results?
Think about asynchronous message events and how to wait for all workers.
Each worker sends messages asynchronously. Listening to their 'message' events and collecting results allows aggregation. Using Promise.all with Promises wrapping each worker's completion is the correct pattern.