Home  >  Article  >  Web Front-end  >  How to Execute Shell Commands in JavaScript Using the \'exec\' Function?

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

Barbara Streisand
Barbara StreisandOriginal
2024-10-19 12:23:30513browse

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.

The above is the detailed content of How to Execute Shell Commands in JavaScript Using the \'exec\' Function?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn