在 Node.js 中设置控制台的字体颜色和样式


你可以使用 chalk 模块 来定制控制台上打印的语句。通过使用它,可以将文本字体颜色更改为任何颜色。还可以将字体样式更改为粗体、斜体或下划线。此外,你可以突出显示打印的文本。

语法

npm install chalk

示例 1

创建文件 "color.js" 并复制以下代码片段。创建文件后,使用命令 "node color.js" 运行此代码。

// Giving color to console statments

// Importing the chalk module
const chalk = require('chalk');

// Printing the text in blue color
console.log(chalk.blue('Welcome to Tutorials Point !'));

// Printing the text in red color
console.log(chalk.red('Error occured !!! '));

// If color is not present we can pass the
// RGB code to give color
console.log(chalk.rgb(100, 150, 70)
            ('Custom statement - Hi...'));

输出

C:\home
ode>> node color.js

示例 2

// Giving color to console statments

// Importing the chalk module
const chalk = require('chalk');

// Setting background color to red
console.log(chalk.bgGreen('Welcome to Tutorials Point'));

// Setting background color to Bright Black
console.log(chalk.bgBlackBright('Hello User !!! '));

// Setting background color to Bright Red
console.log(chalk.bgRedBright('Hello... I am a custom color.'));

输出

C:\home
ode>> node color.js

示例 3

// Giving color to console statments

// Importing the chalk module
const chalk = require('chalk');

// Setting the text style to Bold
console.log(chalk.bold('Welcome to Tutorials Point in bold'));

// Setting the text style to dim
console.log(chalk.dim('Welcome to Tutorials Point in Dim'));

// Setting the text style to Italic
console.log(chalk.italic('Welcome to Tutorials Point in Italic'));

// Setting the text style to Bold
console.log(chalk.underline('Welcome to Tutorials Point in Underline'));

输出

C:\home
ode>> node color.js

更新于: 2021 年 8 月 18 日

784 次浏览

开启你的职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.