{"size": 1990, "ext": "js", "max_stars_repo_path": "perfmon.js", "max_stars_repo_name": "soheilpro/mon", "max_stars_repo_stars_event_min_datetime": "2015-01-19T15:26:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-17T01:31:02.000Z", "max_issues_repo_path": "perfmon.js", "max_issues_repo_name": "soheilpro/mon", "max_issues_repo_issues_event_min_datetime": "2015-04-27T05:50:19.000Z", "max_issues_repo_issues_event_max_datetime": "2016-10-03T18:36:12.000Z", "max_forks_repo_path": "perfmon.js", "max_forks_repo_name": "soheilpro/mon", "max_forks_repo_forks_event_min_datetime": "2015-06-29T13:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-08T14:02:46.000Z"}
{"max_stars_count": 44, "max_issues_count": 4, "max_forks_count": 7, "avg_line_length": 22.6136363636, "max_line_length": 83, "alphanum_fraction": 0.5668341709}
var util = require("util");
var events = require("events");
var spawn = require("child_process").spawn;
var boundary = require("./boundary.js");
var parse = require("csv-parse");
var _ = require("underscore");

function Perfmon(counters) {
  var _this = this;

  _this.counters = counters;
}

util.inherits(Perfmon, events.EventEmitter);

Perfmon.prototype.start = function() {
  var _this = this;

  var typeperf = spawn("typeperf", _this.counters);
  var counters;
  var missingCounterIndexes;

  typeperf.stdout = boundary.delimited(typeperf.stdout);

  typeperf.stdout.on("message", function(message) {
    message = message.toString();

    if (!message)
      return;

    if (message.indexOf("\"") == -1)
      return;

    parse(message, function(error, csv) {
      var row = csv[0];

      if (row[0] == "(PDH-CSV 4.0)") {
        counters = _.rest(row, 1);
        return;
      }

      var host = counters.length > 0 ? /\\\\?([^\\]+)\\/.exec(counters[0])[1] : "";
      var time = new Date(row[0]);
      var values = _.rest(row, 1);

      if (!missingCounterIndexes) {
        missingCounterIndexes = [];

        values.forEach(function (value, index) {
          if (value === "-1")
            missingCounterIndexes.push(index);
        });
      }

      for (var i = missingCounterIndexes.length - 1; i >= 0; i--)
        values.splice(missingCounterIndexes[i], 1);

      if (counters.length !== values.length) {
        _this.emit("error");
        return;
      }

      var result = {
        host: host,
        time: time,
        counters: _.toArray(_.map(_.zip(counters, values), function(item) {
          return {
            name: item[0].replace("\\\\" + host, ""),
            value: parseFloat(item[1])
          };
        }))
      }

      _this.emit("data", result);
    });
  });

  _this.typeperf = typeperf;
};

Perfmon.prototype.stop = function() {
  var _this = this;

  if (_this.typeperf)
    _this.typeperf.kill();
};

module.exports = Perfmon;