Node spawn cant pipe cmd命令

时间:2015-06-07 02:16:11

标签: node.js cmd spawn

您好我正在创建一个插件,该插件使用一些命令行命令以获取进程内存和CPU使用情况,尽管该命令在终端中工作但在与节点一起运行时却没有。

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

以下是来源:

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();
})();

1 个答案:

答案 0 :(得分: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'));
    }
  }
});