"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Execute Shell Commands in JavaScript Using the \'exec\' Function?

How to Execute Shell Commands in JavaScript Using the \'exec\' Function?

Published on 2025-01-28
Browse:845

How to Execute Shell Commands in JavaScript Using the \'exec\' Function?

How to Run Shell Commands with JavaScript

Overview

This guide will demonstrate how to execute shell commands within JavaScript using the child_process module provided by Node's API.

Implementation

To achieve this in JavaScript, you will use the exec function from the child_process module. This function allows you to execute shell commands from within your JavaScript code and access their output.

var exec = require('child_process').exec;

exec('cat *.js bad_file | wc -l',
    function (error, stdout, stderr) {
        console.log('stdout: '   stdout);
        console.log('stderr: '   stderr);
        if (error !== null) {
            console.log('exec error: '   error);
        }
    }
);

In the example above, the exec function is invoked with the shell command cat *.js bad_file | wc -l. This command will execute the cat command to concatenate the contents of all .js files and the non-existent file bad_file. It then pipes the output to the wc -l command, which counts the number of lines in the output.

The exec function takes three additional parameters:

  • stdout: Captures the standard output of the command.
  • stderr: Captures the standard error output of the command, if any.
  • error: Indicates whether an error occurred while executing the command.
Release Statement This article is reproduced in: 1729311256 If there is violations, please contact [email protected] to delete
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3