我想编写一个 JavaScript 函数,它将执行系统 shell 命令(ls例如)并返回值。
我如何实现这一目标?
我想编写一个 JavaScript 函数,它将执行系统 shell 命令(ls例如)并返回值。
我如何实现这一目标?
这里的许多其他答案似乎从浏览器中运行的 JavaScript 函数的角度解决了这个问题。我会假设当提问者说“Shell Script”时他指的是 Node.js 后端 JavaScript,我将进行拍摄和回答。可能使用commander.js来使用你的代码框架:)
您可以使用节点 API 中的child_processmodule。我粘贴了下面的示例代码。
var exec = require('child_process').exec, child;
child = 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);
        }
    });
 child();
希望这可以帮助!
不知道为什么之前的答案给出了各种复杂的解决方案。如果您只想执行像 那样的快速命令ls,则不需要 async/await 或回调或任何东西。这就是你所需要的 - execSync:
const execSync = require('child_process').execSync;
// import { execSync } from 'child_process';  // replace ^ if using ES modules
const output = execSync('ls', { encoding: 'utf-8' });  // the default is 'buffer'
console.log('Output was:\n', output);
对于错误处理,在语句周围添加一个try/catch块。
如果您运行的命令需要很长时间才能完成,那么是的,请查看异步exec函数。
……几年后……
ES6 已被接受为标准,而 ES7 即将到来,因此值得更新答案。我们以 ES6+async/await 和 nodejs+babel 为例,先决条件是:
您的示例foo.js文件可能如下所示:
import { exec } from 'child_process';
/**
 * Execute simple shell command (async wrapper).
 * @param {String} cmd
 * @return {Object} { stdout: String, stderr: String }
 */
async function sh(cmd) {
  return new Promise(function (resolve, reject) {
    exec(cmd, (err, stdout, stderr) => {
      if (err) {
        reject(err);
      } else {
        resolve({ stdout, stderr });
      }
    });
  });
}
async function main() {
  let { stdout } = await sh('ls');
  for (let line of stdout.split('\n')) {
    console.log(`ls: ${line}`);
  }
}
main();
确保你有 babel:
npm i babel-cli -g
安装最新预设:
npm i babel-preset-latest
通过以下方式运行它:
babel-node --presets latest foo.js
这完全取决于 JavaScript 环境。请详细说明。
例如,在 Windows Scripting 中,您可以执行以下操作:
var shell = WScript.CreateObject("WScript.Shell");
shell.Run("command here");
简而言之:
// Instantiate the Shell object and invoke its execute method.
var oShell = new ActiveXObject("Shell.Application");
var commandtoRun = "C:\\Winnt\\Notepad.exe";
if (inputparms != "") {
  var commandParms = document.Form1.filename.value;
}
// Invoke the execute method.  
oShell.ShellExecute(commandtoRun, commandParms, "", "open", "1");