To change the font color of text output to the console in Node.js, you can use ANSI escape codes. ANSI escape codes are special character sequences that can be used to change the formatting of text in the terminal.
To set the font color, you can use the \x1b[3xm
escape code, where x
is a number between 0 and 7 representing the color. For example, to set the font color to red, you can use the \x1b[31m
escape code.
Here’s an example of how to change the font color in the console:
console.log('\x1b[31m%s\x1b[0m', 'This text is red');
In this example, we use the console.log()
function to output a string with the \x1b[31m
escape code at the beginning and the \x1b[0m
escape code at the end. The \x1b[0m
escape code resets the font color to the default.
Here’s a table of the available font colors and their corresponding escape codes:
Color | Escape Code |
---|---|
Black | \x1b[30m |
Red | \x1b[31m |
Green | \x1b[32m |
Yellow | \x1b[33m |
Blue | \x1b[34m |
Magenta | \x1b[35m |
Cyan | \x1b[36m |
White | \x1b[37m |
You can also use the \x1b[3x;4ym
escape code to set the font color and the background color, where x
is a number between 0 and 7 representing the font color and y
is a number between 0 and 7 representing the background color.
Here’s an example of how to change both the font color and the background color in the console:
console.log('\x1b[36;44m%s\x1b[0m', 'This text is cyan on blue');
In this example, we use the console.log()
function to output a string with the \x1b[36;44m
escape code at the beginning and the \x1b[0m
escape code at the end. The \x1b[36;44m
escape code sets the font color to cyan and the background color to blue. The \x1b[0m
escape code resets the font and background colors to their defaults.
Note: ANSI escape codes may not work on all terminals, and they may not be supported by all operating systems. If you need to ensure compatibility with all platforms, you may want to use a third-party library like chalk
to change the console font color.