Simple colorful logging in Node.js
When writing Node.js scripts, I often want to output information to the console in different colors. Usually, it is to get the user's attention and signalize success or error.
I could reach for a battle-tested library like Chalk, but I usually don't need all of its features. Instead, I have a tiny script I copy from project to project:
Then, I can easily log things in color:
"This seems like a very successful message";
"Something might have gone wrong";
"I'm here to inform you of something";
Once executed, it looks like this:
The script uses something called ANSI escape codes. It is a way to give commands to a terminal by passing sequences of bytes, usually starting with an ASCII escape character
\x1b. They are mostly used to move the cursor and to change the color or styling of the text. They are standardized, and they should work on any platform.
\x1b[31m is an escape sequence that tells our terminal to switch color to red. All text after it will be red, until we pass the reset sequence
\x1b[0m, which will revert text to the default color.
If you need more features, I suggest using an existing library. I usually recommend picking one of these two:
- picocolors - when I need more robust but still lightweight library
- Chalk - when I need a fully featured coloring library
But for the sake of learning, I added a few more features and copied code to CodeSandbox. This version allows you to pass multiple parameters, keeps native coloring for objects, and exposes a
paint method which only colors parts of the string.
As a bonus, let's see how we can use color in a browser's console. Escape sequences are not going to work, but we can actually use CSS.
"%c🍋 Lemon", "background: black; color: yellow;";
%c will be styled using CSS defined in the parameter after it.
Open the console in your browser and click on the button below to test it yourself.
And please, just because you have CSS at your disposal, don't go crazy with styling console messages. Your users might not appreciate it.
Have a colorful afternoon!