【问题标题】:Node spawn cant pipe cmd commands节点生成无法管道 cmd 命令
【发布时间】:2015-06-07 02:16:11
【问题描述】:

您好,我正在创建一个插件,该插件使用一些命令行命令来获取进程内存和 cpu 使用情况,尽管该命令在终端中运行,但在使用节点运行时却无法运行。

此外,当使用节点运行时,findstr 部分根本不起作用,因此我从标准输出中获取了所有进程列表。通常我应该有一个 1 行:

这里是来源:

var spawn = require('child_process').spawn;
var readline = require('readline');

function Pstats() {
    this.os = /^win/.test(process.platform) === true ? 'win' : 'nix';
    this.win_cmd_arr = ['/C', 'wmic', 'path', 'Win32_PerfFormattedData_PerfProc_Process', 'get', 'IDProcess,WorkingSet,PercentProcessorTime', '|', 'findstr', '/R', '"^' + process.pid + '"'];

};

// this for example will list all processes with starting pid of 4
// wmic path Win32_PerfFormattedData_PerfProc_Process get IDProcess,WorkingSet,PercentProcessorTime | findstr /R "^4"          

Object.defineProperties(Pstats.prototype, {

    constructor: Pstats,

    usage: {
        enumerable: false,
        value: function(callback) {

            if (this.os === 'win') {

                var proc = spawn('cmd.exe', this.win_cmd_arr);

                proc.stdout.on('data', function(data) {
                    console.log(data.toString());
                });


                // readline.createInterface({
                //     input: proc.stdout,
                //     terminal: false
                // }).on('line', function(line) {
                //     console.log(line);
                // });

                // readline.createInterface({
                //     input: proc.stderr,
                //     terminal: false
                // }).on('line', function(line) {
                //     console.error(line);
                // });

            } else {
                throw new TypeError('unsupported operatin system');
            }

        }

    }

});

exports = module.exports = (function() {
    return new Pstats();
})();

【问题讨论】:

    标签: node.js cmd spawn


    【解决方案1】:

    您可以使用类似 SQL 的 where 子句来限制来自 wmic 的结果。例如:

    var exec = require('child_process').exec;
    
    // ...
    
    function Pstats() {
      this.winCmd = [
        'wmic', 
        'path',
        'Win32_PerfFormattedData_PerfProc_Process',
        'where "IDProcess = ' + process.pid + '"',
        'get',
        ['WorkingSet',
         'PercentProcessorTime'
        ].join(','),
        '/format:csv'
      ].join(' ');
    }
    
    Object.defineProperties(Pstats.prototype, {
      constructor: Pstats,
      usage: {
        enumerable: false,
        value: function(callback) {
          if (process.platform === 'win32') {
            exec(this.winCmd, { encoding: 'utf8' }, function(err, stdout, stderr) {
              if (err)
                return callback(err);
    
              stdout = stdout.split(/\r?\n/g);
              if (stdout.length < 2)
                return callback(new Error('Missing WMIc output'));
    
              var values = stdout[1].split(',');
              if (values.length !== 3)
                return callback(new Error('Bad WMIc output'));
    
              // Node (Computer) name is always the first column with CSV output
              var percentCPU = parseInt(values[1], 10);
              var workingSet = parseInt(values[2], 10);
    
              if (isNaN(percentCPU) || isNaN(workingSet))
                return callback(new Error('Bad WMIc values'));
    
              // `PercentProcessorTime` is uint64 and may not fit in a JS double, so
              // we check for that here and leave it as a string if it does not fit
              if (percentCPU > 9007199254740991)
                percentCPU = values[1];
    
              callback(null, workingSet, percentCPU);
            });
          } else
            callback(new Error('Unsupported platform'));
        }
      }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-07
      • 2011-05-21
      • 1970-01-01
      相关资源
      最近更新 更多