为输出着色
可以使用转义序列在控制台中为文本的输出着色。 转义序列是一组标识颜色的字符。
例如:
console.log('\x1b[33m%s\x1b[0m', '你好')
可以在 Node.js REPL 中进行尝试,它会打印黄色的 你好。
如下图所示:
当然,这是执行此操作的底层方法。 为控制台输出着色的最简单方法是使用库。 Chalk 是一个这样的库,除了为其着色外,它还有助于其他样式的设置(例如使文本变为粗体、斜体或带下划线)。
可以使用 npm install chalk 进行安装,然后就可以使用它:
const chalk = require('chalk')
console.log(chalk.yellow('你好'))
与尝试记住转义代码相比,使用 chalk.yellow 方便得多,并且代码更具可读性。
更多的用法示例,详见项目链接https://github.com/chalk/chalk。
Chalk库 - Terminal string styling done right
强调
- 富有表现力的API
- 高效能
- 嵌套样式的能力
- 256 / Truecolor颜色支持
- 自动检测颜色支持
- 不扩展String.prototype
- 干净而专注
- 积极维护
- 截至2020年1月1日,约有50,000个软件包使用
安装
$ npm install chalk
使用
const chalk = require('chalk');
console.log(chalk.blue('Hello world!'));
Chalk带有易于使用的可组合API,您只需在其中链接和嵌套所需的样式即可。
const chalk = require('chalk');
const log = console.log;
// Combine styled and normal strings
log(chalk.blue('Hello') + ' World' + chalk.red('!'));
// Compose multiple styles using the chainable API
log(chalk.blue.bgRed.bold('Hello world!'));
// Pass in multiple arguments
log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz'));
// Nest styles
log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!'));
// Nest styles of the same type even (color, underline, background)
log(chalk.green(
'I am a green line ' +
chalk.blue.underline.bold('with a blue substring') +
' that becomes green again!'
));
// ES2015 template literal
log(`
CPU: ${chalk.red('90%')}
RAM: ${chalk.green('40%')}
DISK: ${chalk.yellow('70%')}
`);
// ES2015 tagged template literal
log(chalk`
CPU: {red ${cpu.totalPercent}%}
RAM: {green ${ram.used / ram.total * 100}%}
DISK: {rgb(255,131,0) ${disk.used / disk.total * 100}%}
`);
// Use RGB colors in terminal emulators that support it.
log(chalk.keyword('orange')('Yay for orange colored text!'));
log(chalk.rgb(123, 45, 67).underline('Underlined reddish color'));
log(chalk.hex('#DEADED').bold('Bold gray!'));
轻松定义自己的主题:
const chalk = require('chalk');
const error = chalk.bold.red;
const warning = chalk.keyword('orange');
console.log(error('Error!'));
console.log(warning('Warning!'));
利用console.log字符串替换:
const name = 'Sindre';
console.log(chalk.green('Hello %s'), name);
//=> 'Hello Sindre'