Bird
Raised Fist0
Node.jsframework~20 mins

Handling child process errors in Node.js - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Child Process Error Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What happens when a child process emits an 'error' event?
Consider this Node.js code snippet that spawns a child process. What will be logged if the child process fails to start due to an invalid command?
Node.js
import { spawn } from 'child_process';

const child = spawn('invalid_command');

child.on('error', (err) => {
  console.log('Error event:', err.message);
});

child.on('exit', (code) => {
  console.log('Exit event with code:', code);
});
ANo logs appear because the child process silently fails.
BLogs: 'Exit event with code: 1' and no error event is emitted.
CLogs both 'Error event: spawn invalid_command ENOENT' and 'Exit event with code: 0'.
DLogs: 'Error event: spawn invalid_command ENOENT' and no exit event is emitted.
Attempts:
2 left
💡 Hint
The 'error' event is emitted when the process cannot be spawned or killed.
state_output
intermediate
2:00remaining
What is the value of 'exitCode' after a child process error?
Given the following code, what will be the value of 'exitCode' after the child process emits an 'error' event?
Node.js
import { spawn } from 'child_process';

let exitCode = null;
const child = spawn('badcmd');

child.on('error', () => {
  exitCode = 'error_occurred';
});

child.on('exit', (code) => {
  exitCode = code;
});
A'error_occurred'
B0
Cnull
Dundefined
Attempts:
2 left
💡 Hint
Check which event sets the exitCode when the process fails to start.
📝 Syntax
advanced
2:00remaining
Which option correctly attaches an error handler to a child process?
Identify the correct syntax to handle errors from a spawned child process.
Node.js
import { spawn } from 'child_process';
const child = spawn('ls');
Achild.handle('error', (err) => console.error('Error:', err));
Bchild.error((err) => console.error('Error:', err));
Cchild.on('error', (err) => console.error('Error:', err));
Dchild.addEventListener('error', (err) => console.error('Error:', err));
Attempts:
2 left
💡 Hint
Node.js child processes use EventEmitter pattern.
🔧 Debug
advanced
2:00remaining
Why does this child process error handler never run?
Examine the code below. Why does the error handler never log anything even if the command is invalid?
Node.js
import { spawn } from 'child_process';

const child = spawn('invalidcmd');

child.on('exit', (code) => {
  console.log('Exited with code:', code);
});

child.on('close', (code) => {
  console.log('Closed with code:', code);
});
ABecause the 'exit' event only fires on successful commands.
BBecause there is no 'error' event listener attached to the child process.
CBecause 'close' event replaces the 'error' event.
DBecause spawn automatically retries invalid commands silently.
Attempts:
2 left
💡 Hint
Check if the code listens for the 'error' event.
🧠 Conceptual
expert
3:00remaining
What is the correct sequence of events when a child process fails to spawn?
Order the events emitted by a Node.js child process when the spawn command is invalid and fails immediately.
A2 only
B4, 2, 1, 3
C2, 4, 1, 3
D1, 3, 2, 4
Attempts:
2 left
💡 Hint
Consider which events fire when the process never starts.

Practice

(1/5)
1. What is the main reason to listen for the 'error' event when using Node.js child processes?
easy
A. To catch errors that happen when starting or running the child process
B. To get the output data from the child process
C. To close the child process manually
D. To restart the child process automatically

Solution

  1. Step 1: Understand the purpose of the 'error' event

    The 'error' event is triggered if the child process fails to start or encounters a problem during execution.
  2. Step 2: Differentiate from other events

    The 'exit' event tells when the process ends, but 'error' specifically catches startup or runtime errors.
  3. Final Answer:

    To catch errors that happen when starting or running the child process -> Option A
  4. Quick Check:

    'error' event = catch process startup/runtime errors [OK]
Hint: Remember: 'error' means process failed to start or crashed [OK]
Common Mistakes:
  • Confusing 'error' with 'exit' event
  • Thinking 'error' gives output data
  • Assuming 'error' restarts the process
2. Which of the following is the correct way to listen for errors on a child process created with spawn?
easy
A. child.on('error', (err) => { console.error(err); });
B. child.error((err) => { console.error(err); });
C. child.on('exit', (code) => { console.log(code); });
D. child.catch('error', (err) => { console.error(err); });

Solution

  1. Step 1: Recall the correct event listener syntax

    Node.js child processes use on method to listen for events like 'error'.
  2. Step 2: Identify the correct event and method

    child.on('error', (err) => { console.error(err); }); uses child.on('error', callback), which is the proper syntax to catch errors.
  3. Final Answer:

    child.on('error', (err) => { console.error(err); }); -> Option A
  4. Quick Check:

    Use on('error') to catch errors [OK]
Hint: Use child.on('error', callback) to catch errors [OK]
Common Mistakes:
  • Using wrong method like .error() or .catch()
  • Listening to 'exit' instead of 'error' for errors
  • Missing parentheses or wrong event name
3. Consider this code snippet:
const { spawn } = require('child_process');
const child = spawn('node', ['-e', "process.exit(1)"]);
child.on('exit', (code) => {
  console.log('Exit code:', code);
});
child.on('error', (err) => {
  console.error('Error:', err);
});

What will be printed when this runs?
medium
A. Exit code: 0
B. Error: Error message
C. Exit code: 1
D. No output

Solution

  1. Step 1: Understand the child process command

    The child runs a Node.js command that immediately exits with code 1 using process.exit(1).
  2. Step 2: Check which event triggers

    The process exits normally with code 1, so the 'exit' event fires with code 1; no 'error' event occurs.
  3. Final Answer:

    Exit code: 1 -> Option C
  4. Quick Check:

    process.exit(1) triggers 'exit' with code 1 [OK]
Hint: process.exit(n) triggers 'exit' with code n, no 'error' [OK]
Common Mistakes:
  • Thinking exit code 1 triggers 'error' event
  • Expecting 'Exit code: 0' by default
  • Ignoring the 'exit' event output
4. You wrote this code to handle errors:
const { exec } = require('child_process');
const child = exec('invalidcommand');
child.on('exit', (code) => {
  if (code !== 0) console.log('Process failed');
});

Why might this code fail to detect the error properly?
medium
A. Because 'exit' event does not fire on errors
B. Because 'error' event should be used to catch command not found errors
C. Because exec does not emit any events
D. Because the callback function is missing

Solution

  1. Step 1: Understand exec error handling

    When a command is invalid, exec emits an 'error' event, not just an 'exit' event with a code.
  2. Step 2: Identify missing error listener

    The code listens only to 'exit', so it misses errors like 'command not found' which trigger 'error' event.
  3. Final Answer:

    Because 'error' event should be used to catch command not found errors -> Option B
  4. Quick Check:

    Use 'error' event to catch exec command failures [OK]
Hint: Listen to 'error' event for exec command failures [OK]
Common Mistakes:
  • Assuming 'exit' event catches all errors
  • Not adding 'error' event listener
  • Confusing exec with spawn error handling
5. You want to run a child process and handle both startup errors and non-zero exit codes. Which code snippet correctly handles both cases?
hard
A. const child = spawn('mycmd'); child.on('close', (code) => console.log('Process closed with code', code));
B. const child = spawn('mycmd'); child.on('exit', (code) => { if (code !== 0) console.error('Startup error:', code); });
C. const child = spawn('mycmd'); child.on('error', (err) => console.log('Exit code:', err));
D. const child = spawn('mycmd'); child.on('error', (err) => console.error('Startup error:', err)); child.on('exit', (code) => { if (code !== 0) console.log('Exit code:', code); });

Solution

  1. Step 1: Handle startup errors with 'error' event

    Listening to 'error' catches problems starting the process, like command not found.
  2. Step 2: Handle non-zero exit codes with 'exit' event

    The 'exit' event provides the exit code; checking if it's not zero indicates failure.
  3. Step 3: Verify option correctness

    const child = spawn('mycmd'); child.on('error', (err) => console.error('Startup error:', err)); child.on('exit', (code) => { if (code !== 0) console.log('Exit code:', code); }); listens to both 'error' and 'exit' properly and logs appropriate messages.
  4. Final Answer:

    const child = spawn('mycmd'); child.on('error', (err) => console.error('Startup error:', err)); child.on('exit', (code) => { if (code !== 0) console.log('Exit code:', code); }); -> Option D
  5. Quick Check:

    Use 'error' for startup, 'exit' for exit codes [OK]
Hint: Use both 'error' and 'exit' events to cover all errors [OK]
Common Mistakes:
  • Ignoring 'error' event for startup failures
  • Logging exit code as startup error
  • Using only 'close' event without error handling