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

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

Barbara Streisand
Release: 2024-10-19 12:23:30
Original
638 people have browsed it

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);
        }
    }
);
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template