爲輸出着色
可以使用轉義序列在控制檯中爲文本的輸出着色。 轉義序列是一組標識顏色的字符。
例如:
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'