Home  >  Article  >  Web Front-end  >  How to Execute Shell Commands Using JavaScript?

How to Execute Shell Commands Using JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-10-19 12:41:02889browse

How to Execute Shell Commands Using JavaScript?

Executing Shell Commands with JavaScript

Executing system shell commands within JavaScript allows you to interact with the operating system from within your JavaScript code.

Approach:

To execute shell commands in JavaScript, you can utilize Node.js's child_process module. This module provides the exec function, which allows you to run a specified command and capture its output.

Code Example:

const { exec } = require('child_process');

exec('ls *.js bad_file | wc -l', (error, stdout, stderr) => {
  console.log('stdout:', stdout);
  console.log('stderr:', stderr);

  if (error) {
    console.error('exec error:', error);
  }
});

Explanation:

  • The exec function takes a shell command as its first argument.
  • The second argument is a callback function that handles the command's output.
  • Inside the callback function, you can access the stdout, stderr, and error variables to capture the command's output, any error messages, and the error object if an error occurred.

The above is the detailed content of How to Execute Shell Commands Using JavaScript?. 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
Previous article:Proxy Design PatternNext article:Proxy Design Pattern