How to change node.js's console font color?

Better Stack Team
Updated on March 11, 2024

In Node.js, you can change the console font color by using ANSI escape codes. ANSI escape codes are sequences of characters that control text formatting, including colors. Here's a simple example of how you can change the font color in the Node.js console:

 
// ANSI escape codes for text color
const red = '\\x1b[31m';
const green = '\\x1b[32m';
const reset = '\\x1b[0m';

// Use the escape codes to change font color
console.log(red + 'This text is red.' + reset);
console.log(green + 'This text is green.' + reset);

In this example:

  • \\x1b[31m represents the ANSI escape code for setting the text color to red.
  • \\x1b[32m represents the ANSI escape code for setting the text color to green.
  • \\x1b[0m is used to reset the text color to the default.

You can find various ANSI escape codes for different colors and formatting options. Here are a few examples:

  • \\x1b[31m: Red
  • \\x1b[32m: Green
  • \\x1b[33m: Yellow
  • \\x1b[34m: Blue
  • \\x1b[35m: Magenta
  • \\x1b[36m: Cyan
  • \\x1b[37m: White

To create more complex formatting or combine multiple formatting options, you can concatenate the escape codes accordingly.

Keep in mind that ANSI escape codes for colors may not work on all terminals or environments. Some terminals might not support or have disabled ANSI escape codes by default. If you encounter issues, consider using third-party libraries like chalk for more robust and cross-platform color formatting in the console.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github