Executing Shell Commands with Node.js: A Quick Guide

Executing a shell command with Node.js is straightforward and can be done using the built-in child_process module.

This module includes the exec method, which runs a shell command and buffers the output.

Let's look at the code, and then I'll explain quickly.

// Import the child_process module.
const { exec } = require('node:child_process');

// Use exec with an optional callback function
exec('ls -l', (error, stdout, stderr) => {
  if (error) {
    console.error(`exec error: ${error}`);
    return;
  }
  if (stderr) {
    console.error(`stderr: ${stderr}`);
  }
  console.log(`stdout: ${stdout}`);
});

exec executes our command. We pass our command as a string. We then have a second opional parameter with a callback.

ls -l is a command used in Unix-based commands to list files and directories in a long format (-l is the long flag).

Using the callback function, we can access the output if needed (in our case, for adding a simple prepend to our console).

Callback parameters explained

Sometimes you'll want to do something with the output of whatever commands you run. That's where the callback shown in the code example comes in handy.

In the callback, you'll see three parameters: error, stdout, and stderr.

Here's a quick summary of what they are so you can leverage them in whatever you are building:

  • error represents any error that occurred during the execution of the shell command. It is used to indicate issues related to the execution process itself, such as:

    • Command not found or not executable.
    • Insufficient permissions to execute the command.
    • An error in spawning the child process.
    • Issues with the command arguments or syntax.
  • stdout contains the result or output generated by the command execution. The command will be available in stdout if it produces any text-based output. The output is typically a string.

  • stderr represents the standard error output of the command. It contains any error messages, warnings, or other information the command may generate during its execution. This output is separate from the command's regular output (stdout).


If you want to dive in deeper, you can read the full docs here.


Follow me on Twitter or connect on LinkedIn.

🚨 Want to make friends and learn from peers? You can join our free web developer community here. 🎉

NodejsJavaScript
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.