Open In App

How to change Node console font color ?

To change the font color we can use the chalk module in Node as well as the ASCII characters escape codes. We will discuss how to change the font color using both the approaches in this article

Approach 1: Changing color using chalk module

The chalk module is can be used to customize node console with colored text. By using it, one can change console look using features of it like bold the text, making underlines, highlighting the background color of a text, etc.

Command to install chalk:

npm install chalk

Coloring console text with chalk.color:

Text color can be changed by using the chalk.color method like chalk.black, chalk.red, etc.






const chalk = require('chalk');
 
// Printing the text in blue color
console.log(chalk.blue('Hello Geek!'));
 
// Printing the text in red color
console.log(chalk.red('This is an Error! '));
 
// Printing the text in green color
console.log(chalk.rgb(100, 150, 70)
        ('This is in custom color'));

Output:

Coloring background of console text with chalk.bgcolor:

Text background color can be changed by using chalk.bgcolor method like chalk.bgBlack, chalk.bgRed, etc.




const chalk = require('chalk');
 
// Set background color to red
console.log(chalk.bgGreen('Hello Geek!'));
 
// Set background color to BlackBright
console.log(chalk.bgBlackBright('This is an Error! '));
 
// Set background color to WhiteBright
console.log(chalk.bgWhiteBright('This is in custom color'));

Output:

Modifying console text appearance:

Text style can be altered by using the methods like chalk.bold, chalk.italic, etc.




const chalk = require('chalk');
console.log("Text in ", chalk.bold('bold'));
console.log("Text in ", chalk.dim('dim '));
 
// Not widely supported
console.log("Text in ", chalk.italic('italic'));
console.log("Text in ", chalk.underline('underline '));

Output:

Approach 2: Changing font-color with escape codes

We can change the font color of text by using the escape code :

\x1b[3$m

Note: The ‘$’ sign can be replaced with any number between 0 to 7

Color

Escape Code

Black

\x1b[30m

Red

\x1b[31m

Green

\x1b[32m

Yellow

\x1b[33m

Blue

\x1b[34m

Magenta

\x1b[35m

Cyan

\x1b[36m

Blue

\x1b[37m

Example : This example change console font color to magenta.




console.log('\x1b[35m%s\x1b[0m', 'This text is magenta');

Output: The escape code ‘\x1b[0m‘ at the end is to set the text color back to default


Article Tags :