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


在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'));


你可以使用下面的例子: 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


根据这个文档,你可以根据输出的数据类型改变颜色:

// you'll need the util module
var util = require('util');

// let's look at the defaults: 
util.inspect.styles

{ special: 'cyan',
  number: 'yellow',
  boolean: 'yellow',
  undefined: 'grey',
  null: 'bold',
  string: 'green',
  date: 'magenta',
  regexp: 'red' }

// what are the predefined colors?
util.inspect.colors

{ bold: [ 1, 22 ],
  italic: [ 3, 23 ],
  underline: [ 4, 24 ],
  inverse: [ 7, 27 ],
  white: [ 37, 39 ],
  grey: [ 90, 39 ],
  black: [ 30, 39 ],
  blue: [ 34, 39 ],
  cyan: [ 36, 39 ],
  green: [ 32, 39 ],
  magenta: [ 35, 39 ],
  red: [ 31, 39 ],
  yellow: [ 33, 39 ] }

这些似乎是ANSI SGR转义码,其中第一个数字是在输出之前发出的代码,第二个数字是在输出之后发出的代码。因此,如果我们看一下维基百科上的ANSI SGR代码图表,你会发现大多数代码都以数字30-37开始设置前景色,以39结束重置为默认前景色。

我不喜欢的一点是有些颜色太深了。特别是日期。继续,在控制台中尝试new Date()。深色洋红色加黑色真的很难辨认。让我们把它换成浅洋红色。

// first define a new color
util.inspect.colors.lightmagenta = [95,39];

// now assign it to the output for date types
util.inspect.styles.date = 'lightmagenta';

现在,当您尝试new Date()时,输出的可读性大大提高。

如果你想在启动node时自动设置颜色,创建一个脚本来启动repl,就像这样:

// set your colors however desired
var util = require('util');
util.inspect.colors.lightmagenta = [95,39];
util.inspect.styles.date = 'lightmagenta';

// start the repl    
require('repl').start({});

保存这个文件(例如init.js),然后运行node.exe init.js。它将设置颜色并启动node.js命令提示符。

(感谢loganfsmyth对repl想法的回答。)


对于一个不影响String对象的内置方法的流行替代颜色,我推荐使用cli-color。

包括颜色和可链接样式,如粗体、斜体和下划线。

有关此类别中各个模块的比较,请参见这里。


Sindre Sorhus设计的这个图书馆是目前最好的:

粉笔

高性能 不扩展String.prototype 富有表现力的API 嵌套样式的能力 干净和专注 自动检测颜色支持 积极维护 5500+模块使用


Coolors

它非常适合使用或扩展。你可以简单地使用:

var coolors = require('coolors');
console.log(coolors('My cool console log', 'red'));

或者使用config:

var coolors = require('coolors');
console.log(coolors('My cool console log', {
   text: 'yellow',
   background: 'red',
   bold: true,
   underline: true,
   inverse: true,
   strikethrough: true
}));

延伸一下似乎很有趣:

var coolors = require('coolors');
function rainbowLog(msg){
    var colorsText = coolors.availableStyles().text;
    var rainbowColors = colorsText.splice(3);
    var lengthRainbowColors = rainbowColors.length;
    var msgInLetters = msg.split('');
    var rainbowEndText = '';
    var i = 0;
    msgInLetters.forEach(function(letter){
        if(letter != ' '){
            if(i === lengthRainbowColors) i = 0;
            rainbowEndText += coolors(letter, rainbowColors[i]);
            i++;
        }else{
            rainbowEndText += ' ';
        }
    });
    return rainbowEndText;
}
coolors.addPlugin('rainbow', rainbowLog);
console.log(coolorsExtended('This its a creative example extending core with a cool rainbown style', 'rainbown'));

视图Coolors模块


如果你想改变颜色直接自己没有模块尝试

console.log('\x1b[36m', 'sometext' ,'\x1b[0m');

先\x1b[36m改变颜色为36,然后回到终端颜色0。

下面是ANSI颜色代码列表


If you are using Windows CMD then go to the terminal Properties/Colors (CMD top left) and then redefine the RGB value of the offensive color. In my case I believe it's the fifth color square from the left, which I changed to (222,222,222). It does not matter if the currently selected radio button shows Screen Text or Screen Background as you just redefine that specific "system" color. Once you changed the color don't forget to select back the preferred color for the background or text before clicking OK.

更改后,所有来自Node(在我的情况下是Ember)的红色消息都清晰可见。


paint-console

简单的可着色原木。支持检查对象和单行更新 这个包只是重新油漆控制台。

安装

npm install paint-console

使用

require('paint-console');

console.info('console.info();');
console.warn('console.warn();');
console.error('console.error();');
console.log('console.log();');

demo


你也可以使用颜色。

用法:

var cw = require('colorworks').create();
console.info(cw.compile('[[red|Red message with a [[yellow|yellow]] word.]]'));

为了简化工作,您还可以使用它创建一个函数。

function say(msg) {
  console.info(cw.compile(msg));
}

现在你可以做:

say(`[[yellow|Time spent: [[green|${time}]]ms.]]`);

遇到这个问题,想在没有任何依赖的情况下在stdout上使用一些颜色。这结合了其他一些很棒的答案。

这是我得到的。(需要节点v4或更高版本)

// colors.js
const util = require('util')

function colorize (color, text) {
  const codes = util.inspect.colors[color]
  return `\x1b[${codes[0]}m${text}\x1b[${codes[1]}m`
}

function colors () {
  let returnValue = {}
  Object.keys(util.inspect.colors).forEach((color) => {
    returnValue[color] = (text) => colorize(color, text)
  })
  return returnValue
}

module.exports = colors()

只需要文件,然后像这样使用它:

const colors = require('./colors')
console.log(colors.green("I'm green!"))

预定义的颜色代码可以在这里找到


在ubuntu中,你可以简单地使用颜色代码:

var sys = require('sys');
process.stdout.write("x1B[31m" + your_message_in_red + "\x1B[0m\r\n");

node-colorify

提供功能打印文本的颜色,也做文本格式,如粗体,闪烁等。


现在有两种方法来查看Node.js控制台的颜色变化。

一种是通过通用库,这些库可以用颜色标记装饰文本字符串,然后通过标准console.log输出。

今天的顶级图书馆:

粉笔 颜色 cli-color

另一种方法是修补现有的控制台方法。manakin就是这样一个库,它可以让你为所有的控制台方法(log, warn, error和info)自动设置标准颜色。

与通用颜色库的一个显著区别是-它可以全局或局部设置颜色,同时为每个Node.js控制台方法保持一致的语法和输出格式,然后使用这些方法而不必指定颜色,因为它们都是自动设置的。

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

针对你的问题,这里有一个最简单的解决方案:

var con = require('manakin').global;
con.log.color = 30; // Use black color for console.log

它将为应用程序中的每个console.log调用设置黑色。查看更多颜色代码。

manakin使用的默认颜色:


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

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

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

这是控制台中可用颜色(包括背景和前景)的列表,带有一些可用的操作(如重置,反转等)。

const colours = {
    reset: "\x1b[0m",
    bright: "\x1b[1m",
    dim: "\x1b[2m",
    underscore: "\x1b[4m",
    blink: "\x1b[5m",
    reverse: "\x1b[7m",
    hidden: "\x1b[8m",
    
    fg: {
        black: "\x1b[30m",
        red: "\x1b[31m",
        green: "\x1b[32m",
        yellow: "\x1b[33m",
        blue: "\x1b[34m",
        magenta: "\x1b[35m",
        cyan: "\x1b[36m",
        white: "\x1b[37m",
        gray: "\x1b[90m",
        crimson: "\x1b[38m" // Scarlet
    },
    bg: {
        black: "\x1b[40m",
        red: "\x1b[41m",
        green: "\x1b[42m",
        yellow: "\x1b[43m",
        blue: "\x1b[44m",
        magenta: "\x1b[45m",
        cyan: "\x1b[46m",
        white: "\x1b[47m",
        gray: "\x1b[100m",
        crimson: "\x1b[48m"
    }
};

下面是一个如何使用它的例子:

console.log(colours.bg.blue, colours.fg.white, "I am a white message with a blue background", colours.reset) ; 
// Make sure that you don't forget "colours.reset" at the so that you can reset the console back to it's original colours.

或者你可以安装一些实用模块:

npm install console-info console-warn console-error --save-dev

当你使用这些模块时,它们会在控制台显示如下内容:


下面你可以找到运行node.js应用程序时文本的颜色引用:

console.log('\x1b[36m%s\x1b[0m', 'I am cyan');  //cyan
console.log('\x1b[33m%s\x1b[0m', stringToMakeYellow);  //yellow

注意%s是字符串(第二个参数)被注入的位置。\x1b[0m重置终端颜色,因此在此之后它不再继续是所选的颜色。

颜色参考

Reset = "\x1b[0m"
Bright = "\x1b[1m"
Dim = "\x1b[2m"
Underscore = "\x1b[4m"
Blink = "\x1b[5m"
Reverse = "\x1b[7m"
Hidden = "\x1b[8m"

FgBlack = "\x1b[30m"
FgRed = "\x1b[31m"
FgGreen = "\x1b[32m"
FgYellow = "\x1b[33m"
FgBlue = "\x1b[34m"
FgMagenta = "\x1b[35m"
FgCyan = "\x1b[36m"
FgWhite = "\x1b[37m"
FgGray = "\x1b[90m"

BgBlack = "\x1b[40m"
BgRed = "\x1b[41m"
BgGreen = "\x1b[42m"
BgYellow = "\x1b[43m"
BgBlue = "\x1b[44m"
BgMagenta = "\x1b[45m"
BgCyan = "\x1b[46m"
BgWhite = "\x1b[47m"
BgGray = "\x1b[100m"

编辑:

例如,\x1b[31m是一个转义序列,它将被您的终端拦截,并指示它切换到红色。事实上,\x1b是不可打印控制字符转义的代码。仅处理颜色和样式的转义序列也被称为ANSI转义代码,并且是标准化的,因此它们(应该)适用于任何平台。

维基百科对不同终端显示颜色的方式做了很好的比较 https://en.wikipedia.org/wiki/ANSI_escape_code#Colors


我创建了自己的模块StyleMe。我这样做,我可以用很少的打字做很多事情。例子:

var StyleMe = require('styleme');
StyleMe.extend() // extend the string prototype

console.log("gre{Hello} blu{world}!".styleMe()) // Logs hello world! with 'hello' being green, and 'world' being blue with '!' being normal.

它也可以被嵌套:

console.log("This is normal red{this is red blu{this is blue} back to red}".styleMe())

或者,如果你不想扩展字符串原型,你可以选择其他3个选项:

console.log(styleme.red("a string"))
console.log("Hello, this is yellow text".yellow().end())
console.log(styleme.style("some text","red,bbl"))

我不想要任何依赖于此,只有这些在OS x上为我工作。所有其他示例从这里的答案给了我八进制文字错误。

Reset = "\x1b[0m"
Bright = "\x1b[1m"
Dim = "\x1b[2m"
Underscore = "\x1b[4m"
Blink = "\x1b[5m"
Reverse = "\x1b[7m"
Hidden = "\x1b[8m"

FgBlack = "\x1b[30m"
FgRed = "\x1b[31m"
FgGreen = "\x1b[32m"
FgYellow = "\x1b[33m"
FgBlue = "\x1b[34m"
FgMagenta = "\x1b[35m"
FgCyan = "\x1b[36m"
FgWhite = "\x1b[37m"
FgGray = "\x1b[90m"

BgBlack = "\x1b[40m"
BgRed = "\x1b[41m"
BgGreen = "\x1b[42m"
BgYellow = "\x1b[43m"
BgBlue = "\x1b[44m"
BgMagenta = "\x1b[45m"
BgCyan = "\x1b[46m"
BgWhite = "\x1b[47m"
BgGray = "\x1b[100m"

来源:https://coderwall.com/p/yphywg/printing-colorful-text-in-terminal-when-run-node-js-script


我重载了控制台方法。

var colors={
Reset: "\x1b[0m",
Red: "\x1b[31m",
Green: "\x1b[32m",
Yellow: "\x1b[33m"
};

var infoLog = console.info;
var logLog = console.log;
var errorLog = console.error;
var warnLog = console.warn;

console.info= function(args)
{
    var copyArgs = Array.prototype.slice.call(arguments);
    copyArgs.unshift(colors.Green);
    copyArgs.push(colors.Reset);
    infoLog.apply(null,copyArgs);
};

console.warn= function(args)
{
    var copyArgs = Array.prototype.slice.call(arguments);
    copyArgs.unshift(colors.Yellow);
    copyArgs.push(colors.Reset);
    warnLog.apply(null,copyArgs);
};
console.error= function(args)
{
    var copyArgs = Array.prototype.slice.call(arguments);
    copyArgs.unshift(colors.Red);
    copyArgs.push(colors.Reset);
    errorLog.apply(null,copyArgs);
};

// examples
console.info("Numeros",1,2,3);
console.warn("pares",2,4,6);
console.error("reiniciandooo");

输出为。


我为不能有依赖的npm脚本写了一个方便的一行代码:

Const {r, g, b, w, c, m, y, k} = [ ['r', 1], ['g', 2], ['b', 4], ['w', 7], ['c', 6], ['m', 5], ['y', 3], ['k', 0], ].Reduce ((cols, col) => ({ ...关口,[坳[0]]:f = > ' \ x1b[3{坳[1]}美元$ {f} \ x1b [0 m ' }, {}) console.log(' ${g('I')} love ${r('Italy')} ')

R,g,b,w,c,m,y,k分别代表红色,绿色,蓝色,白色,青色,品红,黄色和黑色。


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)
    );
  };
});


这是Windows 10的一种方法(可能适用于7),它改变了cmd, npm终端本身的配色方案(主题),而不仅仅是特定应用程序的控制台输出。

我找到了一个Windows插件——颜色工具,它应该是在Windows保护伞下开发的。在链接中有描述。

我将colortool目录添加到系统环境路径变量中,现在每当我启动终端(NodeJs命令提示符,cmd)时,它都可用。


Reset: "\x1b[0m"
Bright: "\x1b[1m"
Dim: "\x1b[2m"
Underscore: "\x1b[4m"
Blink: "\x1b[5m"
Reverse: "\x1b[7m"
Hidden: "\x1b[8m"

FgBlack: "\x1b[30m"
FgRed: "\x1b[31m"
FgGreen: "\x1b[32m"
FgYellow: "\x1b[33m"
FgBlue: "\x1b[34m"
FgMagenta: "\x1b[35m"
FgCyan: "\x1b[36m"
FgWhite: "\x1b[37m"
FgGray: "\x1b[90m"

BgBlack: "\x1b[40m"
BgRed: "\x1b[41m"
BgGreen: "\x1b[42m"
BgYellow: "\x1b[43m"
BgBlue: "\x1b[44m"
BgMagenta: "\x1b[45m"
BgCyan: "\x1b[46m"
BgWhite: "\x1b[47m"
FgGray: "\x1b[100m"

例如,如果你想有一个昏暗的红色文本和蓝色背景,你可以在Javascript中这样做:

console.log("\x1b[2m", "\x1b[31m", "\x1b[44m", "Sample Text", "\x1b[0m");

颜色和效果的顺序似乎不是那么重要,但总是记得在最后重置颜色和效果。


var to_rgb = function (_text, _r, _g, _b) {
    return "\x1b[38;2;" + _r + ";" + _g + ";" + _b + "m" + _text + "\x1b[0m";
};

此代码帮助设置前景色:\x1b[38;2;R;G;Bm

这在某些地方可能行不通


日志/索引.js

const colors = {
    Reset : "\x1b[0m",
    Bright : "\x1b[1m",
    Dim : "\x1b[2m",
    Underscore : "\x1b[4m",
    Blink : "\x1b[5m",
    Reverse : "\x1b[7m",
    Hidden : "\x1b[8m",

    FgBlack : "\x1b[30m",
    FgRed : "\x1b[31m",
    FgGreen : "\x1b[32m",
    FgYellow : "\x1b[33m",
    FgBlue : "\x1b[34m",
    FgMagenta : "\x1b[35m",
    FgCyan : "\x1b[36m",
    FgWhite : "\x1b[37m",

    BgBlack : "\x1b[40m",
    BgRed : "\x1b[41m",
    BgGreen : "\x1b[42m",
    BgYellow : "\x1b[43m",
    BgBlue : "\x1b[44m",
    BgMagenta : "\x1b[45m",
    BgCyan : "\x1b[46m",
    BgWhite : "\x1b[47m",
};

module.exports = () => {
    Object.keys(colors).forEach(key => {
        console['log' + key] = (strg) => {
            if(typeof strg === 'object') strg = JSON.stringify(strg, null, 4);
            return console.log(colors[key]+strg+'\x1b[0m');
        }
    });
}

app.js

require('./logger')();

然后这样使用它:

console.logBgGreen(" grüner Hintergrund ")

我真的很喜欢@Daniel的回答,但是console.log{color}函数的工作方式与常规的console.log不同。我做了一些更改,现在所有参数的新函数将被传递到console.log(以及颜色代码)。

const _colors = {
    Reset : "\x1b[0m",
    Bright : "\x1b[1m",
    Dim : "\x1b[2m",
    Underscore : "\x1b[4m",
    Blink : "\x1b[5m",
    Reverse : "\x1b[7m",
    Hidden : "\x1b[8m",

    FgBlack : "\x1b[30m",
    FgRed : "\x1b[31m",
    FgGreen : "\x1b[32m",
    FgYellow : "\x1b[33m",
    FgBlue : "\x1b[34m",
    FgMagenta : "\x1b[35m",
    FgCyan : "\x1b[36m",
    FgWhite : "\x1b[37m",

    BgBlack : "\x1b[40m",
    BgRed : "\x1b[41m",
    BgGreen : "\x1b[42m",
    BgYellow : "\x1b[43m",
    BgBlue : "\x1b[44m",
    BgMagenta : "\x1b[45m",
    BgCyan : "\x1b[46m",
    BgWhite : "\x1b[47m",
};

const enableColorLogging = function(){
    Object.keys(_colors).forEach(key => {
        console['log' + key] = function(){
            return console.log(_colors[key], ...arguments, _colors.Reset);
        }
    });
}

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://stackoverflow.com/a/41407246/4808079)非常有用,但不完整。如果你只想给某样东西上色一次,我想这没问题,但我认为以可运行的函数形式共享它更适用于现实生活中的用例。

const Color = {
  Reset: "\x1b[0m",
  Bright: "\x1b[1m",
  Dim: "\x1b[2m",
  Underscore: "\x1b[4m",
  Blink: "\x1b[5m",
  Reverse: "\x1b[7m",
  Hidden: "\x1b[8m",
  
  FgBlack: "\x1b[30m",
  FgRed: "\x1b[31m",
  FgGreen: "\x1b[32m",
  FgYellow: "\x1b[33m",
  FgBlue: "\x1b[34m",
  FgMagenta: "\x1b[35m",
  FgCyan: "\x1b[36m",
  FgWhite: "\x1b[37m",
  FgGray: "\x1b[90m",
  
  BgBlack: "\x1b[40m",
  BgRed: "\x1b[41m",
  BgGreen: "\x1b[42m",
  BgYellow: "\x1b[43m",
  BgBlue: "\x1b[44m",
  BgMagenta: "\x1b[45m",
  BgCyan: "\x1b[46m",
  BgWhite: "\x1b[47m"
  BgGray: "\x1b[100m",
}

function colorString(color, string) {
  return `${color}${string}${Color.Reset}`;
}

function colorLog(color, ...args) {
  console.log(...args.map(
   (it) => typeof it === "string" ? colorString(color, string) : it
  ));
}

像这样使用它:

colorLog(Color.FgYellow, "Some Yellow text to console log", { someObj: true });

console.log([
  colorString(Color.FgRed, "red"),
  colorString(Color.FgGreen, "green"),
  colorString(Color.FgBlue, "blue"),
].join(", "));

这在一定程度上取决于你所在的平台。最常见的方式 要做到这一点,需要打印ANSI转义序列。举个简单的例子, 下面是blender构建脚本中的一些python代码:

// This is a object for use ANSI escape to color the text in the terminal
const bColors = {
    HEADER    : '\033[95m',
    OKBLUE    : '\033[94m',
    OKGREEN   : '\033[92m',
    WARNING   : '\033[93m',
    FAIL      : '\033[91m',
    ENDC      : '\033[0m', 
    BOLD      : '\033[1m',   
    UNDERLINE : '\033[4m'
}

要使用这样的代码,可以执行如下操作

console.log(`${bColors.WARNING} My name is sami ${bColors.ENDC}`)

这适用于(我所知道的)Node控制台。

该包是快捷方式,您可以使用此命令安装它。 Const short = require('@testgrandma/shortcuts');

您可以执行两个命令来更改颜色。它是RGB颜色和Hex颜色short.colorRGB(r,g,b);

short.colorhex(十六进制);

你可以执行console.log(short.colorhex('d50000') + 'This is red!');

包裹可以在这里找到。

https://www.npmjs.com/package/@testgrandma/shortcuts


我在我的snippet目录中创建了一个名为styles.js的文件,我认为它可以帮助任何想要导入单个文件的人。

这是对color.js的styles.js文件的一个小修改,帮助了我很多。

以下是该文件的内容:

// Original: https://github.com/Marak/colors.js/blob/master/lib/styles.js

const styleCodes = {
    // Reset all styles.
    reset: [0, 0],
    
    // Text styles.
    bold: [1, 22],
    dim: [2, 22],
    italic: [3, 23],
    underline: [4, 24],
    inverse: [7, 27],
    hidden: [8, 28],
    strikethrough: [9, 29],
    
    // Foregound classic colours.
    fgBlack: [30, 39],
    fgRed: [31, 39],
    fgGreen: [32, 39],
    fgYellow: [33, 39],
    fgBlue: [34, 39],
    fgMagenta: [35, 39],
    fgCyan: [36, 39],
    fgWhite: [37, 39],
    fgGray: [90, 39],
    
    // Foreground bright colours.
    fgBrightRed: [91, 39],
    fgBrightGreen: [92, 39],
    fgBrightYellow: [93, 39],
    fgBrightBlue: [94, 39],
    fgBrightMagenta: [95, 39],
    fgBrightCyan: [96, 39],
    fgBrightWhite: [97, 39],

    // Background basic colours.
    bgBlack: [40, 49],
    bgRed: [41, 49],
    bgGreen: [42, 49],
    bgYellow: [43, 49],
    bgBlue: [44, 49],
    bgMagenta: [45, 49],
    bgCyan: [46, 49],
    bgWhite: [47, 49],
    bgGray: [100, 49],
    bgGrey: [100, 49],
    
    // Background bright colours.
    bgBrightRed: [101, 49],
    bgBrightGreen: [102, 49],
    bgBrightYellow: [103, 49],
    bgBrightBlue: [104, 49],
    bgBrightMagenta: [105, 49],
    bgBrightCyan: [106, 49],
    bgBrightWhite: [107, 49],
};

// This object will contain the string representation for all style codes.
const styles = {};

// Loop over all the style codes and assign them to the `styles` object.
// 
// The a `styleCode` in the `styleCodes` object consists of two numbers:
// Index 0: The opening style code (In HTML this can be the opening <b> tag).
// Index 1: The closing style code (In HTML this can be the closing </b> tag).
for (let styleCode of Object.keys(styleCodes)) {
    styles[styleCode] = {
        open: `\x1B[${styleCodes[styleCode][0]}m`,
        close: `\x1B[${styleCodes[styleCode][1]}m`,
    };
}

module.exports = styles;

其实用起来很简单。

const styles = require("/path/to/styles.js");

// Let's say we've got an error:
const errorOpen = styles.bold.open + styles.bgRed.open + styles.fgWhite.open;
const errorClose = styles.reset.close; // Close everything
console.log(errorOpen, "ERROR", errorClose, ": Missing semicolon at line 9.");

内联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);


另一种方法是使用一个简单的ANSI代码生成器。

您不需要安装软件包 不需要搜索颜色代码,只需点击按钮

GIF演示

你可以在https://console-colors.vercel.app/上使用它

公共存储库:https://github.com/alecshoppe/console-colors


如果你想保持简单,而不使用任何外部模块/学习新的api /破解核心控制台功能:

const LCERROR = '\x1b[31m%s\x1b[0m'; //red
const LCWARN = '\x1b[33m%s\x1b[0m'; //yellow
const LCINFO = '\x1b[36m%s\x1b[0m'; //cyan
const LCSUCCESS = '\x1b[32m%s\x1b[0m'; //green

const logger = class {
  static error(message, ...optionalParams) { console.error(LCERROR, message, ...optionalParams) }
  static warn(message, ...optionalParams) { console.warn(LCWARN, message, ...optionalParams) }
  static info(message, ...optionalParams) { console.info(LCINFO, message, ...optionalParams) }
  static success(message, ...optionalParams) { console.info(LCSUCCESS, message, ...optionalParams) }
}

// then instead (as presented in the accepted answer)
// console.error(LCERROR, 'Error message in red.');
// you write:

logger.error('Error message in red.');

// or with multiple parameters (only the message will be red):

logger.error('Error message in red.', 1, false, null, {someKey: 'whatever'});

// or use backticks (template literal) instead multiple params:

logger.error(`This will be red as ${foo} and ${bar} too.`);

现在您可以像使用控制台一样使用记录器。没有新的API需要记住……通常你会把它放到一个模块(logger.js)中,并导出类,以便在你的应用程序中随处使用它,因为const logger = require('./logger');


最小的别名:

{
  const f = (color) => (...args) => {
    for (const x of [color, ...args, "\33[0m"]) console.log(x);
  };

  Object.assign(console, {
    black: f("\33[30m"),
    red: f("\33[31m"),
    green: f("\33[32m"),
    yellow: f("\33[33m"),
    blue: f("\33[34m"),
    magenta: f("\33[35m"),
    cyan: f("\33[36m"),
    white: f("\33[37m"),
  });
}

// Usage
console.blue("Blue world");