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.
0
0
Handling child process errors in Node.js
Introduction
Running a script or command from your Node.js app and you want to know if it fails.
Starting a background task and needing to handle if it crashes or exits unexpectedly.
Executing system commands and wanting to show a friendly message if something goes wrong.
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
This example runs the 'ls -l' command and logs an error if it fails to start.
Node.js
import { spawn } from 'child_process'; const child = spawn('ls', ['-l']); child.on('error', (err) => { console.error('Failed to start process:', err.message); });
This listens for the child process to finish and checks if it ended with an error code.
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'); } });
This shows how to catch an error when trying to run a command that does not exist.
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'); } });
OutputSuccess
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.