由于眼睛的问题,我不得不将控制台背景色改为白色,但字体是灰色的,它使消息无法阅读。我怎样才能改变呢?


当前回答

内联typescript解决方案

export const color = (function (colors) {
    const fn = (code: number, str: string) => `\x1b[${code}m${str}\x1b[39m`;
    const obj = { grey: fn.bind(null, 90) };
    for (let i = 0; i < colors.length; i++) obj[colors[i]] = fn.bind(null, 30 + i);
    return obj as { [K in typeof colors[any] | 'grey']: (str: string) => string };
})(['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'] as const);

其他回答

在Node.js中有多个可用于格式化控制台文本的包。最流行的有:

粉笔, cli-color - 颜色- >编辑:颜色不再推荐,因为它有拒绝服务漏洞 详情见:https://snyk.io/blog/open-source-npm-packages-colors-faker/

用法:

粉笔:

const chalk = require('chalk');
console.log(chalk.red('Text in red'));

CLI-COLOR:

const clc = require('cli-color');
console.log(clc.red('Text in red'));

没有库,没有复杂,只是简单:

console.log(red('Error!'));

function red(s) {
    return '\033[31m' + s;
}

2017:

简单的方法,为消息添加时间颜色,你不需要改变你的代码,使用keep your console.log('msg')或console.err('error')

var clc = require("cli-color");
var mapping = {
  log: clc.blue,
  warn: clc.yellow,
  error: clc.red
};

["log", "warn", "error"].forEach(function(method) {
  var oldMethod = console[method].bind(console);
  console[method] = function() {
    oldMethod.apply(
      console,
      [mapping[method](new Date().toISOString())]
      .concat(arguments)
    );
  };
});

var colorSet = {
    Reset: "\x1b[0m",
    Red: "\x1b[31m",
    Green: "\x1b[32m",
    Yellow: "\x1b[33m",
    Blue: "\x1b[34m",
    Magenta: "\x1b[35m"
};

var funcNames = ["info", "log", "warn", "error"];
var colors = [colorSet.Green, colorSet.Blue, colorSet.Yellow, colorSet.Red];

for (var i = 0; i < funcNames.length; i++) {
    let funcName = funcNames[i];
    let color = colors[i];
    let oldFunc = console[funcName];
    console[funcName] = function () {
        var args = Array.prototype.slice.call(arguments);
        if (args.length) {
            args = [color + args[0]].concat(args.slice(1), colorSet.Reset);
        }
        oldFunc.apply(null, args);
    };
}

// Test:
console.info("Info is green.");
console.log("Log is blue.");
console.warn("Warn is orange.");
console.error("Error is red.");
console.info("--------------------");
console.info("Formatting works as well. The number = %d", 123);

你可以使用下面的例子: https://help.ubuntu.com/community/CustomizingBashPrompt

也是nodeJs的一个要旨

例如,如果你想让部分文本显示为红色,只需执行console.log with:

"\033[31m this will be red \033[91m and this will be normal"

基于此,我为Node.js创建了“colog”扩展。你可以使用以下方法安装:

npm install colog

回购和npm: https://github.com/dariuszp/colog