CodeBlanks Logo Icon CodeBlanks

Child process

Learn to run child processes with child_process.exec.

child_process.exec

child_process.exec runs a shell command as a child process. You receive the command's output through a callback. This is used to run system commands from inside Node.js.

For example, with exec("echo hello", (err, stdout, stderr) => { console.log(stdout); }) you run the echo command and print its output. The callback takes three parameters: err for errors, stdout for normal output and stderr for error output. The callback is called when the command finishes. For large outputs spawn is more suitable, but for short commands exec is simpler.

The exec callback

The callback of exec takes three parameters: (err, stdout, stderr). If the command runs successfully, err is null; stdout holds the output and stderr holds error messages.

The output usually carries a trailing newline, so cleaning it with stdout.trim() is common. For example, exec("node --version", (err, stdout) => console.log(stdout.trim())) prints the Node.js version. If the command is not found or returns a non-zero exit code, err is set. That is why checking if (err) at the top of the callback is a good habit.

Practice Run an echo command and print the output

Import exec from the child_process module. Run the command with exec("echo merhaba", cb). Inside the callback, print stdout.trim() with console.log.

Starter code

index.js
// Import child_process
// Run "echo merhaba" with exec
// Print stdout in the callback
// write here

Sample solution

index.js
const { exec } = require("child_process");
exec("echo merhaba", (err, stdout) => {
  console.log(stdout.trim());
});

Expected output

merhaba

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Import child_process

Question
const { exec } = require("____");
Answer
const { exec } = require("child_process");

Explanation: exec is imported from the child_process module.

2 Match each piece to its role

Term Meaning
exec Runs a command
stdout Output stream
stderr Error stream
callback Handles the result

3 What does the second parameter of the exec callback contain?

index.js
(err, stdout, stderr)
  • The exit code
  • The error object
  • stdout output Correct answer
  • The PID number

Explanation: The second parameter is stdout, the normal output of the command.

All lessons in Intermediate