How to use util - 10 common examples

To help you get started, we’ve selected a few util examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github googleapis / cloud-debug-nodejs / test / misc / test-leak.ts View on Github external
function test() {
  iters++;

  const bp = {id: 'fake-breakpoint', location: {path: __filename, line: 4}};
  v8debugapi.set(bp);
  v8debugapi.clear(bp);

  if (iters % 100 === 0) {
    console.log(iters + ' ' + util.inspect(process.memoryUsage()));
  }

  // infinite loop
  setImmediate(test);
}
github rupnikj / nodeimu / testSync.js View on Github external
function dispAccel() {
  var tic = new Date(); 
  var data = IMU.getValueSync();
  var toc = new Date();

  var str = data.timestamp.toISOString() + " ";
  str += print_vector3("Accel", data.accel)
  // str += print_vector3("Gyro", data.gyro)
  // str += print_vector3("Compass", data.compass)
  // str += print_vector3("Fusion", data.fusionPose)

  var str2 = "";
  if (data.temperature && data.pressure && data.humidity) {
    var str2 = util.format(' %s %s %s', data.temperature.toFixed(4), data.pressure.toFixed(4), data.humidity.toFixed(4));
  }
  console.log(str + str2);
  num++;
  if (num == numStop) {
    console.timeEnd("sync");
  } else {
    setTimeout(dispAccel, 50 - (toc - tic));
  }
}
github apigee / trireme / node12 / node12tests / trireme / test-util-inspect.js View on Github external
assert(/TypeError: FAIL/.test(util.inspect(new TypeError('FAIL'))));
assert(/SyntaxError: FAIL/.test(util.inspect(new SyntaxError('FAIL'))));
try {
  undef();
} catch (e) {
  assert(/ReferenceError.*undef/.test(util.inspect(e)));
}
var ex = util.inspect(new Error('FAIL'), true);
assert.ok(ex.indexOf('[Error: FAIL]') != -1);
// Rhino doesn't put stack on Error constructor yet
//assert.ok(ex.indexOf('[stack]') != -1);
//assert.ok(ex.indexOf('[message]') != -1);

// GH-1941
// should not throw:
assert.equal(util.inspect(Object.create(Date.prototype)), '{}');

// GH-1944
assert.doesNotThrow(function() {
  var d = new Date();
  d.toUTCString = null;
  util.inspect(d);
});

assert.doesNotThrow(function() {
  var r = /regexp/;
  r.toString = null;
  util.inspect(r);
});

// bug with user-supplied inspect function returns non-string
assert.doesNotThrow(function() {
github nodekit-io / nodekit-darwin / test / lib-test / spec-node / utilSpec.js View on Github external
it('should pass testPrint', function() {
    // only assures we don't fail - doesn't test the actual result
    util.print('message to stdout', 'and', {});
  });
github mgcrea / generator-angular-component / app / index.js View on Github external
global.d.apply(null, arguments);
  util.log((new Error()).stack);
  process.exit(1);
};

var Generator = module.exports = function Generator(args, options, config) {
  yeoman.generators.Base.apply(this, arguments);

  this.on('end', function () {
    this.installDependencies({ skipInstall: options['skip-install'] });
  });

  this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};

util.inherits(Generator, yeoman.generators.Base);

Generator.prototype.askFor = function askFor() {
  var done = this.async();

  // Have Yeoman greet the user.
  console.log(this.yeoman);

  // var props = this.props = {
  //   ngVersion: '~1.2.10',
  //   locale: 'fr',
  //   ngModules: ['animate', 'cookies', 'route', 'sanitize'],
  //   components: ['bootstrap:~3.1.0', 'angular-strap:~2.0.0', 'font-awesome:~4.0.0'],
  //   cssPreprocessor: 'less',
  //   supportLegacy: 'yes',
  //   name: path.basename(process.env.PWD),
  //   license: 'MIT',
github repetere / periodicjs / public / extensions / periodicjs.ext.admin / javascripts / item.js View on Github external
this.emit('newListener', type,
              util.isFunction(listener.listener) ?
              listener.listener : listener);

  if (!this._events[type])
    // Optimize the case of one listener. Don't need the extra array object.
    this._events[type] = listener;
  else if (util.isObject(this._events[type]))
    // If we've already got an array, just append.
    this._events[type].push(listener);
  else
    // Adding the second element, need to change to array.
    this._events[type] = [this._events[type], listener];

  // Check for listener leak
  if (util.isObject(this._events[type]) && !this._events[type].warned) {
    var m;
    if (!util.isUndefined(this._maxListeners)) {
      m = this._maxListeners;
    } else {
      m = EventEmitter.defaultMaxListeners;
    }

    if (m && m > 0 && this._events[type].length > m) {
      this._events[type].warned = true;
      console.error('(node) warning: possible EventEmitter memory ' +
                    'leak detected. %d listeners added. ' +
                    'Use emitter.setMaxListeners() to increase limit.',
                    this._events[type].length);
      console.trace();
    }
  }
github holdfenytolvaj / pogi / src / queryWhere.ts View on Github external
} else {
        let parts = strip(key.split(jsonRegexp));

        field = parts.shift();
        quotedField = util.format('"%s"', field);

        if (parts.length > 1) {
            let jsonOp = parts.shift();
            let jsonKey = parts.shift();

            // treat numeric json keys as array indices, otherwise quote it
            if (isNaN(jsonKey) && jsonKey.indexOf("'") == -1) {
                jsonKey = util.format("'%s'", jsonKey);
            }

            quotedField = util.format('%s%s%s', quotedField, jsonOp, jsonKey);
        }
    }


    if (operation.fieldMutator) {
        quotedField = operation.fieldMutator(field, quotedField);
    }


    return {
        field: field,
        quotedField: quotedField,
        operator: (operation.operator || '=').toUpperCase(),
        mutator: operation.mutator,
        originalOp: userOp
    };
github rajeshdavidbabu / Node-Clone-S3-Bucket / lib / helpers / file_ops.js View on Github external
// @ts-check

'use strict';

const fs = require('graceful-fs');
const { promisify } = require('util');

const mkdirPromise = promisify(fs.mkdir);

module.exports = () => ({
  createDirectoryAsync(dirPath) {
    return mkdirPromise(dirPath, { recursive: true });
  },

  _getDirPathFromFilePath(filePath) {
    let filePathArr = filePath.split('/');
    filePathArr.pop();
    return filePathArr.join('/');
  },

  getWriteStream(filePath) {
    // extract dir path from file path.
    const dirPath = this._getDirPathFromFilePath(filePath);
    return this.createDirectoryAsync(dirPath)
github keymetrics / app-playground / node_modules / pmx / lib / index.js View on Github external
PMX.initModule = function(opts, cb) {
  if (!opts) opts = {};

  opts = util._extend({
    alert_enabled    : true,
    widget           : {}
  }, opts);

  opts.widget = util._extend({
    type : 'generic',
    logo : 'https://app.keymetrics.io/img/logo/keymetrics-300.png',
    theme            : ['#111111', '#1B2228', '#807C7C', '#807C7C']
  }, opts.widget);

  opts.isModule = true;
  opts = Configuration.init(opts);

  // Force error catching
  PMX.catchAll();
github megamsys / varai / varai / nodes / flows.js View on Github external
var i;
	var nt;
	missingTypes = [];

	for ( i = 0; i < activeConfig.length; i++) {
		var type = activeConfig[i].type;
		// TODO: remove workspace in next release+1
		if (type != "workspace" && type != "tab") {
			nt = typeRegistry.get(type);
			if (!nt && missingTypes.indexOf(type) == -1) {
				missingTypes.push(type);
			}
		}
	}
	if (missingTypes.length > 0) {
		util.log("[varai] Waiting for missing types to be registered:");
		for ( i = 0; i < missingTypes.length; i++) {
			util.log("[varai]  - " + missingTypes[i]);
		}
		return;
	}

	util.log("[varai] Starting flows");
	events.emit("nodes-starting");
	for ( i = 0; i < activeConfig.length; i++) {
		var nn = null;
		// TODO: remove workspace in next release+1
		if (activeConfig[i].type != "workspace" && activeConfig[i].type != "tab") {
			nt = typeRegistry.get(activeConfig[i].type);
			if (nt) {
				try {
					nn = new nt(activeConfig[i]);