Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a child process using Node.js.
Node.js
const { spawn } = require('[1]');
const child = spawn('ls', ['-lh', '/usr']); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'fs' or 'http' instead of 'child_process' to spawn processes.
✗ Incorrect
Node.js uses the child_process module to create child processes.
2fill in blank
mediumComplete the code to listen for data from the child process's stdout.
Node.js
child.stdout.on('[1]', (data) => { console.log(`Output: ${data}`); });
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'exit' or 'close' event instead of 'data' to get output.
✗ Incorrect
The data event is emitted when the child process sends output.
3fill in blank
hardFix the error in the code to correctly handle child process exit.
Node.js
child.on('[1]', (code) => { console.log(`Child exited with code ${code}`); });
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'close' event instead of 'exit' to detect process end.
✗ Incorrect
The exit event is emitted when the child process ends.
4fill in blank
hardFill both blanks to create a child process that runs a script and handle errors.
Node.js
const child = require('child_process').[1]('node', ['script.js']); child.on('[2]', (err) => { if (err) console.error('Error:', err); });
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'exit' event to catch errors instead of 'error'.
Using 'fork' when 'spawn' is intended.
✗ Incorrect
spawn starts a new process, and error event handles errors.
5fill in blank
hardFill all three blanks to create a child process, listen for output, and handle exit.
Node.js
const { [1] } = require('child_process');
const child = [2]('ls', ['-la']);
child.on('[3]', (code) => {
console.log(`Process ended with code ${code}`);
}); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up 'fork' and 'spawn'.
Listening for 'close' instead of 'exit' event.
✗ Incorrect
Destructure spawn from the child_process module, use spawn to create the process, and listen for exit event.