Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a new worker thread.
Node.js
const { Worker } = require('worker_threads');
const worker = new [1]('./worker.js'); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using ChildProcess instead of Worker for threads
Using lowercase 'worker' which is not a class
Confusing Process with Worker
✗ Incorrect
In Node.js, Worker is used to create a new worker thread.
2fill in blank
mediumComplete the code to spawn a child process using Node.js.
Node.js
const { spawn } = require('child_process');
const child = spawn('[1]', ['-lh', '/usr']); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'node' which runs Node.js, not a shell command
Using 'worker' or 'thread' which are not shell commands
✗ Incorrect
The spawn function runs a command; here, ls lists directory contents.
3fill in blank
hardFix the error in the worker thread message listener.
Node.js
worker.on('message', ([1]) => { console.log('Received:', data); });
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different parameter name than the one used inside the function
Using 'msg' or 'message' but logging 'data'
✗ Incorrect
The parameter name must match the variable used inside the function. Here, data is used, so the parameter should be data.
4fill in blank
hardFill both blanks to send a message from the main thread to the worker.
Node.js
worker.[1]({ text: 'Hello' }); worker.[2]('exit', () => console.log('Worker exited'));
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'send' which is for child processes, not worker threads
Using 'emit' instead of 'on' to listen for events
✗ Incorrect
Use postMessage to send data to a worker thread, and on to listen for events like 'exit'.
5fill in blank
hardFill all three blanks to create a child process and handle its output.
Node.js
const { [1] } = require('child_process');
const child = [2]('node', ['script.js']);
child.stdout.on('[3]', data => console.log(`Output: ${data}`)); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'exec' instead of 'spawn' which behaves differently
Listening for wrong event names like 'output' or 'message'
✗ Incorrect
Import spawn from 'child_process', use it to create the child process, and listen for 'data' events on stdout.