在下面,您可以找到运行 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"
BgBlack = "\x1b[40m"
BgRed = "\x1b[41m"
BgGreen = "\x1b[42m"
BgYellow = "\x1b[43m"
BgBlue = "\x1b[44m"
BgMagenta = "\x1b[45m"
BgCyan = "\x1b[46m"
BgWhite = "\x1b[47m"
编辑:
例如, \x1b[31m
是一个转义序列,它将被您的终端截获并指示其切换为红色。实际上, \x1b
是不可打印控制字符escape
的代码。只处理颜色和样式的转义序列也称为ANSI 转义代码,并且已标准化,因此(应)在任何平台上都可以使用。
Wikipedia 很好地比较了不同终端如何显示颜色https://en.wikipedia.org/wiki/ANSI_escape_code#Colors
有多个软件包可用于在 Node.js 中格式化控制台文本。最受欢迎的是:
粉笔:
const chalk = require('chalk');
console.log(chalk.red('Text in red'));
颜色:
const colors = require('colors');
console.log('Text in red'.red);
CLI 颜色:
const clc = require('cli-color');
console.log(clc.red('Text in red'));
许多人注意到他们不赞成更改String 原型colors
。如果您希望保留原型,请使用以下代码:
const colors = require('colors/safe');
console.log(colors.red('Text in red'));
如果您想自己直接更改颜色而无需模块,请尝试
console.log('\x1b[36m', 'sometext' ,'\x1b[0m');
首先\x1b[36m
将颜色更改为36
,然后返回到终端颜色0
。