【问题标题】:How To Execute Windows Shell Commands (Cmd.exe) with Node JS如何使用 Node JS 执行 Windows Shell 命令 (Cmd.exe)
【发布时间】:2013-04-01 21:51:18
【问题描述】:

我愿意

C:\>ACommandThatGetsData > save.txt

但不是在控制台中解析和保存数据,我想用 Node.JS

执行上述命令

如何使用 Node.JS 执行 shell 命令?

【问题讨论】:

标签: node.js cmd windows-shell


【解决方案1】:

使用process.execPath():

process.execPath('/path/to/executable');

更新

我应该更好地阅读文档。

有一个Child Process Module 允许执行子进程。您将需要child_process.execchild_process.execFilechild_process.spawn。所有这些在使用上都是相似的,但每个都有自己的优点。使用哪一个取决于您的需求。

【讨论】:

    【解决方案2】:

    你也可以试试node-cmd 包:

    const nodeCmd = require('node-cmd');
    nodeCmd.get('dir', (err, data, stderr) => console.log(data));
    

    【讨论】:

    • 这解决了我碰到的砖墙!谢谢:)
    【解决方案3】:

    我知道这个问题很老,但它帮助我使用 Promise 找到了我的解决方案。 另见:this question & answer

    const util = require('util');
    const exec = util.promisify(require('child_process').exec);
    
    async function runCommand(command) {
      const { stdout, stderr, error } = await exec(command);
      if(stderr){console.error('stderr:', stderr);}
      if(error){console.error('error:', error);}
      return stdout;
    }
    
    
    async function myFunction () {
        // your code here building the command you wish to execute ...
        const command = 'dir';
        const result = await runCommand(command);
        console.log("_result", result);
        // your code here processing the result ...
    }
    
    // just calling myFunction() here so it runs when the file is loaded
    myFunction();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-14
      • 1970-01-01
      • 1970-01-01
      • 2013-09-22
      • 1970-01-01
      • 1970-01-01
      • 2014-09-19
      • 2011-01-18
      相关资源
      最近更新 更多