When you run another program from your Node.js app, things can go wrong. Handling errors helps you catch problems and keep your app running smoothly.
Handling child process errors in Node.js
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Node.js
import { spawn } from 'child_process'; const child = spawn('command', ['arg1', 'arg2']); child.on('error', (err) => { // handle error here }); child.on('exit', (code, signal) => { // handle exit here });
Use the 'error' event to catch problems like the command not found or permission denied.
The 'exit' event tells you when the child process finishes, with its exit code or signal.
Examples
Node.js
import { spawn } from 'child_process'; const child = spawn('ls', ['-l']); child.on('error', (err) => { console.error('Failed to start process:', err.message); });
Node.js
import { spawn } from 'child_process'; const child = spawn('node', ['someScript.js']); child.on('exit', (code) => { if (code !== 0) { console.log(`Process exited with code ${code}`); } else { console.log('Process completed successfully'); } });
Node.js
import { spawn } from 'child_process'; const child = spawn('fakeCommand'); child.on('error', (err) => { console.error('Error event caught:', err.message); });
Sample Program
This program runs a small Node.js script as a child process that prints a message and exits with code 1. It listens for output, errors, and exit events to handle all cases.
Node.js
import { spawn } from 'child_process'; // Try to run a command that may fail const child = spawn('node', ['-e', 'console.log("Hello from child"); process.exit(1);']); child.stdout.on('data', (data) => { console.log(`Child output: ${data.toString().trim()}`); }); child.on('error', (err) => { console.error(`Failed to start child process: ${err.message}`); }); child.on('exit', (code, signal) => { if (code !== 0) { console.log(`Child process exited with code ${code}`); } else { console.log('Child process exited successfully'); } });
Important Notes
Always listen for the 'error' event to catch startup problems.
The exit code 0 means success; any other code usually means an error.
Use 'stdout' and 'stderr' streams to get output and error messages from the child process.
Summary
Handling child process errors helps your app stay stable when running other programs.
Listen to 'error' and 'exit' events to know what happens with the child process.
Check exit codes and output to understand success or failure.
Practice
1. What is the main reason to listen for the
'error' event when using Node.js child processes?easy
Solution
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.Step 2: Differentiate from other events
The 'exit' event tells when the process ends, but 'error' specifically catches startup or runtime errors.Final Answer:
To catch errors that happen when starting or running the child process -> Option AQuick 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
Solution
Step 1: Recall the correct event listener syntax
Node.js child processes useonmethod to listen for events like 'error'.Step 2: Identify the correct event and method
child.on('error', (err) => { console.error(err); }); useschild.on('error', callback), which is the proper syntax to catch errors.Final Answer:
child.on('error', (err) => { console.error(err); }); -> Option AQuick Check:
Useon('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:
What will be printed when this runs?
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
Solution
Step 1: Understand the child process command
The child runs a Node.js command that immediately exits with code 1 usingprocess.exit(1).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.Final Answer:
Exit code: 1 -> Option CQuick 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:
Why might this code fail to detect the error properly?
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
Solution
Step 1: Understand exec error handling
When a command is invalid, exec emits an 'error' event, not just an 'exit' event with a code.Step 2: Identify missing error listener
The code listens only to 'exit', so it misses errors like 'command not found' which trigger 'error' event.Final Answer:
Because 'error' event should be used to catch command not found errors -> Option BQuick 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
Solution
Step 1: Handle startup errors with 'error' event
Listening to 'error' catches problems starting the process, like command not found.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.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.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 DQuick 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
