如何更改node.js的控制台字体颜色?

Mai*_*tor 481 console colors node.js

由于眼睛问题,我不得不将控制台背景颜色更改为白色,但字体是灰色的,这使得消息不可读.我该怎么改变它?

bod*_*di0 918

在运行node.js应用程序时,您可以在下面找到要命令的文本颜色参考:

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

注意%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"

BgBlack = "\x1b[40m"
BgRed = "\x1b[41m"
BgGreen = "\x1b[42m"
BgYellow = "\x1b[43m"
BgBlue = "\x1b[44m"
BgMagenta = "\x1b[45m"
BgCyan = "\x1b[46m"
BgWhite = "\x1b[47m"
Run Code Online (Sandbox Code Playgroud)

编辑:

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

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

  • 我接受了这个问题,因为它是最懒惰的,有很多颜色,没有依赖性.如果你想要更简单的解决方案*和*依赖关系,请检查@ nelsonic的答案,它建议非常简单的库. (31认同)
  • 你在哪里找到这个参考?颜色值中的每个字符是什么意思? (7认同)
  • @ giorgos29cm [→见这里](http://bluesock.org/~willkg/dev/ansi.html).顺便说一句,添加一个`1;`用于鲜艳的颜色,即"\ x1b [1; 34m"==浅蓝色... (7认同)
  • 我已经接受了这个答案并将其稍微更改为可运行的代码。/sf/answers/3997036361/ (3认同)
  • 打印到文件而不是控制台时,如何防止显示这些字符? (2认同)

nel*_*nic 283

Node.js中有多个可用于格式化控制台文本的包.最受欢迎的是:

用法:


粉笔:

const chalk = require('chalk');
console.log(chalk.red('Text in red'));
Run Code Online (Sandbox Code Playgroud)

CLI-COLOR:

const clc = require('cli-color');
console.log(clc.red('Text in red'));
Run Code Online (Sandbox Code Playgroud)

颜色:

const colors = require('colors');
console.log('Text in red'.red);
Run Code Online (Sandbox Code Playgroud)

很多人都注意到他们不赞成colors改变String原型.如果您希望保留原型,请使用以下代码:

const colors = require('colors/safe');
console.log(colors.red('Text in red'));
Run Code Online (Sandbox Code Playgroud)

  • 颜色现在有:`var colors = require('colors/safe');`然后使用`colors.red('left string all alone')` (8认同)
  • 虽然我同意MattJohnson的回答(重写util.inpect方法的默认颜色 - 见下文)比使用颜色模块越好,颜色模块需要*零安装*和符合*绝大多数用户的需求*这简直是改变console.log输出的颜色.当然,"搞乱内置插件"很糟糕(同意100%),但没有*部署*代码应该包含console.log语句,所以让我们务实一点.@devundef使用单元测试将额外的String方法添加到原型混乱中吗? (3认同)
  • @devundef同意你在String对象中添加方法.可能值得一提到GitHub上的模块作者.和/或建议具有类似简单程度的替代模块/方法. (2认同)

Hen*_*eng 145

如果你想直接改变颜色而不用模块试试

console.log('\x1b[36m', 'sometext' ,'\x1b[0m');
Run Code Online (Sandbox Code Playgroud)

首先'\ x1b [36m'将颜色更改为"36"然后再返回到终端颜色"0".

这是ANSI颜色代码列表

  • 以下是ANSI终端代码,http://telepathy.freedesktop.org/doc/telepathy-glib/telepathy-glib-debug-ansi.html (25认同)
  • 感谢您提及如何重置颜色. (15认同)
  • 如何更改字体样式,例如粗体红色、斜体绿色? (2认同)

小智 68

为您的输出着色您可以使用其中的示例:https:
//help.ubuntu.com/community/CustomizingBashPrompt

也是nodeJs要点

例如,如果您想要部分文本为红色,请使用以下命令执行console.log:

"\033[31m this will be red \033[91m and this will be normal"
Run Code Online (Sandbox Code Playgroud)

基于此我为Node.js创建了"colog"扩展.您可以使用以下方法安装它

npm install colog
Run Code Online (Sandbox Code Playgroud)

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

  • `\ 033 [31m`有效,但`\ 033 [91m`没有.对于Ubuntu终端,它应该是`\ 033 [0m`. (14认同)
  • 第一个链接似乎已经死了. (11认同)
  • 并且八进制转义似乎不起作用:`error:八进制转义序列"\ 033 [31mServer ready @#{app.get('port')}\033 [91m"不允许 (4认同)
  • `\ 033 [0m`应该用于将文本恢复正常,而不是'\ 033 [91m` (4认同)

ARS*_*S81 32

如果您想保持简单而不使用任何外部模块/学习新的 API/破解核心console功能:

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.`);
Run Code Online (Sandbox Code Playgroud)

logger现在您可以像使用 一样使用 your console。没有需要记住的新 API...通常您会将其放入模块 (logger.js) 并导出class以便能够在应用程序中的任何位置使用它,如下所示const logger = require('./logger');


Moj*_*ini 31

表情符号

您可以使用其他人在答案中提到的文本颜色。

但是您可以使用表情符号代替!例如,您可以??用于警告消息和错误消息。

或者简单地将这些笔记本用作颜色:

: error message
: warning message
: ok status message
: action message
: canceled status message
: Or anything you like and want to recognize immediately by color
Run Code Online (Sandbox Code Playgroud)

奖金:

这种方法还可以帮助您直接在源代码中快速扫描和查找日志。

例如:

: error message
: warning message
: ok status message
: action message
: canceled status message
: Or anything you like and want to recognize immediately by color
Run Code Online (Sandbox Code Playgroud)

某些 Linux 发行版的默认表情符号字体在默认情况下可能不是彩色的,您可能希望首先将它们设置为彩色。


如何打开表情符号选择器?

MAC OS control +command+space

窗户 win +.

linux : control +.control+;

  • 提示:在 *Win10* 上,您可以按 `[Win] + [.]` 打开特殊的表情符号窗口:) (3认同)

Mat*_*int 28

根据此文档,您可以根据输出的数据类型更改颜色:

// 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 ] }
Run Code Online (Sandbox Code Playgroud)

这些似乎是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';
Run Code Online (Sandbox Code Playgroud)

现在,当您尝试时new Date(),输出更具可读性.

如果您想在启动节点时自动设置颜色,请创建一个启动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({});
Run Code Online (Sandbox Code Playgroud)

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

(感谢loganfsmyth在这个 repl想法的答案中.)


Abd*_*UMI 27

这是可用操作(重置,反向,...)的控制台中可用颜色(背景,前景)的列表.

const colors = {
 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",
  Crimson: "\x1b[38m" //???????
 },
 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",
  Crimson: "\x1b[48m"
 }
};
Run Code Online (Sandbox Code Playgroud)

使用方法如下:

 console.log(colors.bg.Blue, colors.fg.White , "I am white message with blue background", colors.Reset) ; 
 //don't forget "colors.Reset" to stop this color and return back to the default color
Run Code Online (Sandbox Code Playgroud)

你也可以安装:

npm install console-info console-warn console-error --save-dev
Run Code Online (Sandbox Code Playgroud)

IT将为您提供更接近客户端控制台的输出:

在此输入图像描述

  • 我正在使用相同的并且工作正常但由于某种原因 Dim 没有做任何事情?我想要灰色效果,所以认为使用带有昏暗效果的白色会导致灰色,但只有白色打印不会变暗。任何的想法? (2认同)

cal*_*lum 19

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

粉笔

  • 高效率
  • 不延伸 String.prototype
  • 富有表现力的API
  • 能够嵌套样式
  • 干净,专注
  • 自动检测颜色支持
  • 积极维护
  • 由5500+模块使用

  • 是的,但它的另一个依赖 (2认同)

Shn*_*hnd 18

颜色代码如上所述

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"
Run Code Online (Sandbox Code Playgroud)

例如,如果你想要一个带有蓝色背景的Dim,Red文本,你可以在Javascript中这样做:

console.log("\x1b[2m", "\x1b[31m", "\x1b[44m", "Sample Text", "\x1b[0m");
Run Code Online (Sandbox Code Playgroud)

颜色和效果的顺序似乎并不那么重要,但始终要记住在最后重置颜色和效果.

  • @Sergey 我正在使用 Windows 并在 CMD 和 Powershell 中尝试过,但两者都不起作用 (2认同)

chr*_*lly 12

我为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) => ({
  ...cols,  [col[0]]: f => `\x1b[3${col[1]}m${f}\x1b[0m`
}), {})

console.log(`${g('I')} love ${r('Italy')}`)
Run Code Online (Sandbox Code Playgroud)


use*_*584 10

对于一种流行的颜色选择,不会搞乱String对象的内置方法,我建议检查cli-color.

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

有关此类别中各种模块的比较,请参见此处.


way*_*ure 8

没有图书馆没有并发症很简单:

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

function red(s) {
    return '\033[31m' + s;
}
Run Code Online (Sandbox Code Playgroud)

  • 当您发现它不能以控制台处理对象的方式处理对象时,这并不简单,并且它不尊重控制台流类型或 TTY 支持,这会产生更多问题。这只是一个会带来很多问题的黑客。 (3认同)

Mar*_*ark 7

您可以创建一个coloring.ts文件并将一组以下函数放入其中。

export let bright = (input: any) => '\x1b[1m' + input + '\x1b[0m'
export let dim = (input: any) => '\x1b[2m' + input + '\x1b[0m'
export let underscore = (input: any) => '\x1b[4m' + input + '\x1b[0m'
export let blink = (input: any) => '\x1b[5m' + input + '\x1b[0m'
export let reverse = (input: any) => '\x1b[7m' + input + '\x1b[0m'
export let hidden = (input: any) => '\x1b[8m' + input + '\x1b[0m'

export let black = (input: any) => '\x1b[30m' + input + '\x1b[0m'
export let red = (input: any) => '\x1b[31m' + input + '\x1b[0m'
export let green = (input: any) => '\x1b[32m' + input + '\x1b[0m'
export let yellow = (input: any) => '\x1b[33m' + input + '\x1b[0m'
export let blue = (input: any) => '\x1b[34m' + input + '\x1b[0m'
export let magenta = (input: any) => '\x1b[35m' + input + '\x1b[0m'
export let cyan = (input: any) => '\x1b[36m' + input + '\x1b[0m'
export let white = (input: any) => '\x1b[37m' + input + '\x1b[0m'
export let gray = (input: any) => '\x1b[90m' + input + '\x1b[0m'

export let bgBlack = (input: any) => '\x1b[40m' + input + '\x1b[0m'
export let bgRed = (input: any) => '\x1b[41m' + input + '\x1b[0m'
export let bgGreen = (input: any) => '\x1b[42m' + input + '\x1b[0m'
export let bgYellow = (input: any) => '\x1b[43m' + input + '\x1b[0m'
export let bgBlue = (input: any) => '\x1b[44m' + input + '\x1b[0m'
export let bgMagenta = (input: any) => '\x1b[45m' + input + '\x1b[0m'
export let bgCyan = (input: any) => '\x1b[46m' + input + '\x1b[0m'
export let bgWhite = (input: any) => '\x1b[47m' + input + '\x1b[0m'
export let bgGray = (input: any) => '\x1b[100m' + input + '\x1b[0m'
Run Code Online (Sandbox Code Playgroud)

然后您可以按如下方式使用它们:

console.log(`${blue('42')}:${yellow('00')}:${magenta('07')}`)
Run Code Online (Sandbox Code Playgroud)

着色示例


小智 6

遇到了这个问题,并想在标准输出上使用一些颜色而没有任何依赖性。这结合了这里的其他一些很好的答案。

这就是我所拥有的。(需要节点 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()
Run Code Online (Sandbox Code Playgroud)

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

const colors = require('./colors')
console.log(colors.green("I'm green!"))
Run Code Online (Sandbox Code Playgroud)

预定义的颜色代码可在此处获得


vit*_*y-t 6

今天有两种方法可以看到改变Node.js控制台的颜色.

一种是通过通用库来装饰带有颜色标签的文本字符串,然后通过标准输出console.log.

今天的顶级图书馆:

另一种方式 - 修补现有的控制台方法.这种库之一- 侏儒鸟可以自动为你的所有控制台设置方法标准颜色(log,warn,errorinfo).

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

由于眼睛问题,我不得不将控制台背景颜色更改为白色,但字体是灰色的,这使得消息不可读.我该怎么改变它?

特别针对您的问题,这是最简单的解决方案:

var con = require('manakin').global;
con.log.color = 30; // Use black color for console.log
Run Code Online (Sandbox Code Playgroud)

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

manakin使用的默认颜色:

在此输入图像描述


Ron*_*ite 6

我重载了控制台方法.

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");
Run Code Online (Sandbox Code Playgroud)

输出是. 在此输入图像描述


小智 5

油漆控制台

简单的彩色日志。支持检查对象和单行更新这个包只是重新绘制控制台。

安装

npm install paint-console
Run Code Online (Sandbox Code Playgroud)

用法

require('paint-console');

console.info('console.info();');
console.warn('console.warn();');
console.error('console.error();');
console.log('console.log();');
Run Code Online (Sandbox Code Playgroud)

演示


Luk*_*kas 5

我不想对此有任何依赖,只有这些在 OS X 上对我Octal literal有用。这里答案中的所有其他示例都给了我错误。

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"
Run Code Online (Sandbox Code Playgroud)

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


小智 5

记录器/index.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');
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

应用程序.js

require('./logger')();
Run Code Online (Sandbox Code Playgroud)

然后像这样使用它:

console.logBgGreen(" grüner Hintergrund ")
Run Code Online (Sandbox Code Playgroud)


Ser*_*gey 5

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);
Run Code Online (Sandbox Code Playgroud)


Sep*_*eed 5

我发现上面的这个答案(/sf/answers/2898507251/)非常有用,但不完整。如果你只想给某个东西上色一次,我想它会很好,但我认为以可运行的函数形式共享它更适用于现实生活中的用例。

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",

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

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

function colorStringLog(color, string) {
  console.log(colorString(color, string));
}
Run Code Online (Sandbox Code Playgroud)

像这样使用它:

colorStringLog(Color.FgYellow, "Some Yellow text to console log");

console.log([
  colorString(Color.FgRed, "red"),
  colorString(Color.FgGreen, "green"),
  colorString(Color.FgBlue, "blue"),
].join(", "));
Run Code Online (Sandbox Code Playgroud)


小智 5

这在某种程度上取决于您在哪个平台上。最常见的方法是打印 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'
}
Run Code Online (Sandbox Code Playgroud)

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

console.log(`${bColors.WARNING} My name is sami ${bColors.ENDC}`)
Run Code Online (Sandbox Code Playgroud)

  • 我得到“严格模式下不允许八进制转义序列”。 (2认同)