colors.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. let FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM, isTTY=true;
  2. if (typeof process !== 'undefined') {
  3. ({ FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM } = process.env || {});
  4. isTTY = process.stdout && process.stdout.isTTY;
  5. }
  6. const $ = exports.$ = {
  7. enabled: !NODE_DISABLE_COLORS && NO_COLOR == null && TERM !== 'dumb' && (
  8. FORCE_COLOR != null && FORCE_COLOR !== '0' || isTTY
  9. )
  10. }
  11. function init(x, y) {
  12. let rgx = new RegExp(`\\x1b\\[${y}m`, 'g');
  13. let open = `\x1b[${x}m`, close = `\x1b[${y}m`;
  14. return function (txt) {
  15. if (!$.enabled || txt == null) return txt;
  16. return open + (!!~(''+txt).indexOf(close) ? txt.replace(rgx, close + open) : txt) + close;
  17. };
  18. }
  19. // modifiers
  20. exports.reset = init(0, 0);
  21. exports.bold = init(1, 22);
  22. exports.dim = init(2, 22);
  23. exports.italic = init(3, 23);
  24. exports.underline = init(4, 24);
  25. exports.inverse = init(7, 27);
  26. exports.hidden = init(8, 28);
  27. exports.strikethrough = init(9, 29);
  28. // colors
  29. exports.black = init(30, 39);
  30. exports.red = init(31, 39);
  31. exports.green = init(32, 39);
  32. exports.yellow = init(33, 39);
  33. exports.blue = init(34, 39);
  34. exports.magenta = init(35, 39);
  35. exports.cyan = init(36, 39);
  36. exports.white = init(37, 39);
  37. exports.gray = init(90, 39);
  38. exports.grey = init(90, 39);
  39. // background colors
  40. exports.bgBlack = init(40, 49);
  41. exports.bgRed = init(41, 49);
  42. exports.bgGreen = init(42, 49);
  43. exports.bgYellow = init(43, 49);
  44. exports.bgBlue = init(44, 49);
  45. exports.bgMagenta = init(45, 49);
  46. exports.bgCyan = init(46, 49);
  47. exports.bgWhite = init(47, 49);