all files / lib/ raw.js

89.29% Statements 25/28
63.16% Branches 12/19
100% Functions 6/6
89.29% Lines 25/28
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71                                                                                           
'use strict';
 
const util = require('util');
const tty = require('tty');
const os = require('os');
 
const colorCache = {};
const colors = ['red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'gray', 'grey'];
 
const pid = process.pid;
const hostname = os.hostname();
 
const raw = module.exports = {
 
  //formatter
  fmt: util.format.apply.bind(util.format, util),
 
  stringify: function (args, params) {
    Iif(args.length === 1 && args[0] instanceof Error && params.stack) {
      // print stack
      const e = args[0];
      return [
        e.stack,
        'pid: ' + pid,
        'Host: ' + hostname,
        'URL: ' + (e.url || ''),
        'Date: ' + (new Date()).toISOString()
      ].join(os.EOL);
    }
    return raw.fmt(args);
  },
 
  //stdout
  stdout: function (text) {
    process.stdout.write(text + '\n');
  },
 
  stderr: function (text) {
    process.stderr.write(text + '\n');
  },
 
  withColor: function (target) {
    Iif(process.env.DISABLE_COLOR && process.env.DISABLE_COLOR !== 'false') {
      return false;
    }
    if(target === 'stdout') {
      return tty.isatty(1);
    }
    Eif(target === 'stderr') {
      return tty.isatty(2);
    }
  },
 
  randomColor: function (name) {
    let color;
    if(name) {
      color = colorCache[name];
      if(!color) {
        color = colorCache[name] = this.randomColor();
      }
    } else {
      color = colors[Math.floor(Math.random() * colors.length)];
    }
    return color;
  },
 
  renderWithRandomColor: function (name) {
    return require('colors')[this.randomColor(name)](name);
  }
};