0
0
Node.jsframework~5 mins

exec for running shell commands in Node.js

Choose your learning style9 modes available
Introduction

We use exec to run commands on the computer's shell from a Node.js program. This helps us automate tasks or get system info.

You want to list files in a folder from your Node.js app.
You need to run a system command like checking disk space.
You want to automate running scripts or tools outside Node.js.
You want to get the output of a shell command to use in your program.
Syntax
Node.js
const { exec } = require('child_process');

exec('command', (error, stdout, stderr) => {
  if (error) {
    console.error(`Error: ${error.message}`);
    return;
  }
  if (stderr) {
    console.error(`Stderr: ${stderr}`);
    return;
  }
  console.log(`Output: ${stdout}`);
});

exec runs the command as a string in the shell.

The callback gets error, stdout (normal output), and stderr (error output).

Examples
This lists files in the current folder on Unix-like systems.
Node.js
const { exec } = require('child_process');

exec('ls', (error, stdout, stderr) => {
  if (!error && !stderr) {
    console.log(stdout);
  }
});
This lists files in the current folder on Windows.
Node.js
const { exec } = require('child_process');

exec('dir', (error, stdout, stderr) => {
  if (!error && !stderr) {
    console.log(stdout);
  }
});
This gets the installed Node.js version.
Node.js
const { exec } = require('child_process');

exec('node -v', (error, stdout, stderr) => {
  if (!error && !stderr) {
    console.log(`Node version: ${stdout.trim()}`);
  }
});
Sample Program

This program runs a simple shell command that prints a message. It shows how to handle errors and print the output.

Node.js
const { exec } = require('child_process');

exec('echo Hello from shell', (error, stdout, stderr) => {
  if (error) {
    console.error(`Error: ${error.message}`);
    return;
  }
  if (stderr) {
    console.error(`Stderr: ${stderr}`);
    return;
  }
  console.log(`Output: ${stdout.trim()}`);
});
OutputSuccess
Important Notes

Always handle errors to avoid your program crashing.

Be careful with user input in commands to avoid security risks.

exec runs commands asynchronously, so your program keeps running while waiting.

Summary

exec lets Node.js run shell commands easily.

Use it to automate or get info from the system.

Always check for errors and output carefully.