0
0
NodejsHow-ToBeginner · 3 min read

How to Use exec in Node.js: Syntax and Examples

In Node.js, you use exec from the child_process module to run shell commands asynchronously. It runs a command in a new shell and returns the output via a callback function.
📐

Syntax

The exec function runs a shell command asynchronously and calls a callback with the results.

  • command: The shell command to run as a string.
  • options: Optional settings like environment variables or working directory.
  • callback: Function called when the command finishes, with error, stdout, and stderr.
javascript
const { exec } = require('child_process');

exec(command, options, (error, stdout, stderr) => {
  // handle results here
});
💻

Example

This example runs the ls -l command to list files in the current directory and prints the output or error.

javascript
const { exec } = require('child_process');

exec('ls -l', (error, stdout, stderr) => {
  if (error) {
    console.error(`Error: ${error.message}`);
    return;
  }
  if (stderr) {
    console.error(`Stderr: ${stderr}`);
    return;
  }
  console.log(`Output:\n${stdout}`);
});
Output
Output: total 8 -rw-r--r-- 1 user staff 1234 Apr 27 10:00 file1.txt -rw-r--r-- 1 user staff 5678 Apr 27 10:00 file2.txt
⚠️

Common Pitfalls

Common mistakes include not handling errors, assuming synchronous behavior, or running commands without sanitizing inputs which can cause security risks.

Always check error and stderr in the callback to catch problems.

javascript
const { exec } = require('child_process');

// Wrong: ignoring errors
exec('invalidcommand', (error, stdout, stderr) => {
  console.log(stdout); // This will be empty or undefined
});

// Right: handle errors properly
exec('invalidcommand', (error, stdout, stderr) => {
  if (error) {
    console.error(`Error: ${error.message}`);
    return;
  }
  console.log(stdout);
});
📊

Quick Reference

  • exec(command, options, callback): Run a shell command asynchronously.
  • error: Error object if command fails.
  • stdout: Standard output from the command.
  • stderr: Standard error output from the command.
  • Use for simple commands; for streaming output, consider spawn.

Key Takeaways

Use exec from child_process to run shell commands asynchronously in Node.js.
Always handle error and stderr in the callback to catch command failures.
exec buffers the entire output; for large data or streaming, use spawn instead.
Never run shell commands with unsanitized user input to avoid security risks.
The callback receives three arguments: error, stdout, and stderr.