Emitted 'error' event on ChildProcess instance

14 min read

The "error" event is emitted on a ChildProcess instance when an error occurs while executing the child process.

Here is an example of how you can handle the "error" event on a ChildProcess instance:

const { spawn } = require('child_process');

const child = spawn('ls', ['-l']); // Run the "ls -l" command

child.on('error', (err) => {
  console.error(`Error occurred: ${err.message}`);
});

child.on('exit', (code) => {
  console.log(`Child process exited with code ${code}`);
});

In the example above, if an error occurs while executing the child process (e.g., the command "ls" does not exist), the "error" event will be emitted and the error message will be logged to the console. The "exit" event is also listened for to handle the case when the child process exits.