0
0
Node.jsframework~5 mins

Child process exit codes in Node.js

Choose your learning style9 modes available
Introduction

Child process exit codes tell you if a program finished successfully or had an error. They help you understand what happened after running another program inside your Node.js app.

You run a script or command from your Node.js app and want to know if it worked.
You want to handle errors when a child process stops unexpectedly.
You need to perform different actions based on how a child process ended.
You want to log or debug why a child process failed.
You want to clean up resources only if the child process finished correctly.
Syntax
Node.js
childProcess.on('exit', (code, signal) => {
  // code is the exit code number or null
  // signal is the termination signal or null
});

The code is a number where 0 means success and other numbers mean errors.

The signal tells if the process was stopped by a system signal like SIGTERM.

Examples
This runs the ls -lh command and logs the exit code when done.
Node.js
const { spawn } = require('child_process');
const ls = spawn('ls', ['-lh']);

ls.on('exit', (code) => {
  console.log(`Child exited with code ${code}`);
});
This runs a Node.js script and checks the exit code inside the callback.
Node.js
const { exec } = require('child_process');
exec('node someScript.js', (error, stdout, stderr) => {
  if (error) {
    console.log(`Error code: ${error.code}`);
  } else {
    console.log('Script ran successfully');
  }
});
This starts a sleep command, kills it, and logs the exit code and signal.
Node.js
const { spawn } = require('child_process');
const proc = spawn('sleep', ['10']);

proc.kill('SIGTERM');
proc.on('exit', (code, signal) => {
  console.log(`Exit code: ${code}, Signal: ${signal}`);
});
Sample Program

This program runs a child Node.js process that exits with code 1. It listens for the exit event and prints the exit code. If the process was killed by a signal, it prints that instead.

Node.js
import { spawn } from 'child_process';

const child = spawn('node', ['-e', "process.exit(1)"]);

child.on('exit', (code, signal) => {
  if (code !== null) {
    console.log(`Child process exited with code ${code}`);
  } else if (signal !== null) {
    console.log(`Child process was killed by signal ${signal}`);
  } else {
    console.log('Child process exited');
  }
});
OutputSuccess
Important Notes

Exit code 0 means success; any other number usually means an error.

If the process is terminated by a signal, the exit code will be null and the signal will be set.

Always listen for the exit event to know when the child process finishes.

Summary

Child process exit codes tell if a process finished well or had errors.

Use the exit event to get the code and signal.

Code 0 means success; other codes or signals mean problems.