Lewis Cianci I'm a passionate mobile-first developer, and I've been making apps with Flutter since it first released. I also use ASP.NET 5 for web. Given the chance, I'll talk to you for far too long about why I love Flutter so much.

Using console colors with Node.js

7 min read 2094

Using Console Colors With Node.js

Editor’s note: Since the release of this blog post, Color.js was corrupted and reverted to its previous version of 1.4.0. While you can still use the older version of Color.js, use it with caution or use one of the other alternatives mentioned in this article.

Since the rise of Node.js, we’ve seen more and more console apps released than ever before. Sometimes if you don’t need the complexity of writing a UI, the console output is enough. But, by default, a Node.js app’s output renders as simple white text on a black background.

This means that it’s easy to clutter your view of the app or miss important bits of information. In this article, we’ll learn how to implement console colors and how to use Chalk, Colors.js, and Color-CLI to help us.

Issues with a lack of console color in Node.js apps

Let’s imagine our example app below uses Node.js to connect to an endpoint and retrieve some data.

We’re not actually doing any of the heavy-lifting when connecting to these endpoints, rather, we’re simply producing an output that we can normally expect to see from an app like this.

However, in an app like this, we’d be tempted to write text as an output to our console. Maybe we’re incredibly busy and don’t feel like we have the time to add colors to our app, or it simply doesn’t cross our minds.

Whatever the reason may be, the output of our simple console Node.js app looks like this:

Output Of A Simple Console Node.js App

If you read the output as the creator of the program, you know what to look for, see that there are quite a few connection attempts before the connection succeeds, with only a partial result set received, and you know how to fix it.

But, if you work in a team and other people use this script, different people can interpret the results differently.

If this script ran as part of a scheduled operation or as a part of a larger series of scripts, there’s a good chance that people would skip to the last line, and understand All finished as everything working as intended.

To give our users the right impression, we can use visual aspects to clearly indicate if everything worked as intended or if something failed. That’s where our console colors come in.

Implementing console colors in Node.js apps

To use console colors in our Node.js app, we must first understand what’s happening under the hood.



Programs producing text outputs have been around for decades, so the standards involved that let us make these color changes can feel a little primitive. We must understand how we can use an escape code to signal to the console that we want to change the output’s color.

Normally, our console prints the text that we supply to it via console.log. However, if we send an escape character (\x1b) and a certain sequence ([33m )to the console, the console actually catches the sequence before printing it, thus allowing basic terminal configuration.

In this case, we use it to tell the console that we want to change the color.

We then need to accomplish two things: first, we must change the color of our text to what we want, and second, we must reset the color of the console back to what it was before we changed it. Otherwise, all output after that time will be the color that we chose.

So, if we wanted to print, “Welcome to the app!” in yellow, this would be our console.log statement:

console.log('\x1b[33m Welcome to the app! \x1b[0m');

And the result looks like this:

Changing The Color Output

Even though we have our yellow string, what on earth is going on with the square brackets and the backslashes? Let’s break it down.

Using control characters to color our output

\x1b is a control character that indicates to the console that we want to do something that isn’t related to actually printing text to the console. Everything written after this control character, on the same line, configures the terminal in some way.

After our control character, we specify what we would like to do. In this case, we want to change to the yellow character for our foreground, which has an ID of 33 in the ANSI color chart. By placing [33m after our initial control character, we switch the console output color to yellow.

We have quite a few colors to choose from, but there are some pros and cons to this approach.

The good news is that we introduce no new dependencies on our Node.js project, and our app will produce the correct colors on millions of computers around the world.

The bad news is that our code becomes slightly cryptic. People won’t intuitively know that we set our console characters through this string, and maintaining this code in the future can become a problem.

It’s also annoying to reference a table when all we want to do is color our console output. We must also remember to always put \x1b[0m after using colors so the console resets back to the default color scheme.

Fortunately, as is usually the case in the Node.js world, there’s not just one package that can help us. We’ll look at three popular options for CLI colors.

Chalk

Chalk is a simple way to bring console colors into your Node.js project. The last commit occurred on November 26, and a major version was just released (v5.0.0).

Another nice feature of Chalk is that it doesn’t extend String.prototype. Extending native objects in JavaScript essentially changes the implementation of a built-in function and is usually regarded as a poor idea.

This is because if library 1 sets a function on String like .colorify, and then library 2 sets its own function of .colorify on the String implementation, the second library would override the first. That’s obviously a pretty big issue to debug.

The syntax is also easy to understand and use.

For our code sample, let’s assign console.log to a constant value of log so we can access it a little easier. Then, we can use the chalk function with the appropriate function calls to get the colors that we want.

To demonstrate this, quickly bootstrap a Nodejs application by creating a project directory and from that directory run:

npm init -y

And install chalk by running:

npm install chalk

Next, create a file named console.js. You can do this with the CLI by running:

touch console.js

Add the code below to the console.js file:

import chalk from 'chalk';

const log = console.log;
chalk.level = 1; // Use colours in the VS Code Debug Window
log(chalk.yellow('Welcome to the app!'));
for (var i = 0; i <= 10; i++){
    log(chalk.white('Attempting to connect to endpoint, attempt ' + i));
}

log(chalk.green('Connection established! Sending statistics'));
log(chalk.red('Not all statistics are available...'));
log(chalk.redBright('Endpoint disconnected before all results were received'));
log(chalk.magenta('All finished'));

Update our package.json file to use ES6 modules by adding "type": "module" to the list of properties in the package.json file. You can add this below the "name": "chalk", property.

Finally, update the scripts section by replacing the code with:

 "scripts": {
    "start": "node console.js"
  },

Now, we can test our app and see chalk in action by running:

And the output is as follows:

Using Chalk To Change Output Colors

Obviously, your tastes may vary, and you might not want to use so many colors in your console app. But, they’re there if you ever want to use them.

Assigning basic themes with Chalk

We also have the option to assign some basic themes to our colors. For example, to set a universal color for our errors or warnings, it’s as simple as assigning the appropriate functions to names, like so:

import chalk from 'chalk';

const error = chalk.red;
const warning = chalk.bgRed; // Orange color

console.log(error('Error!'));
console.log(warning('Warning!'));

You can replace the code in the console.js with the code above and run:

npm start

The output of this code is as expected:

Assign A Universal Color For Errors Or Warnings

You can mix and match these styles as much as you want and as much as your app requires.

Colors.js

Colors.js is another way to change up the colors within your Node.js app. However, it does extend the String.prototype. We’ve already gone over why this is usually a bad idea, but it does make for a slightly easier invocation of colors within your app.

The last commit to Colors.js was in January 2020. There are probably only so many ways you can color a console, but without any changes in the last two years at the time of writing, it’s probably safe to assume it’s been abandoned at this point.

That doesn’t mean it doesn’t work, though, but you should be aware that support could be harder to come by if you use it.

To use Colors.js, create a project directory. From the project directory, initialize a Node.js project by running:

npm init -y

And install color.js by running:

npm install colors

Now create a console.js file inside the project directory with the following code:

var colors = require('colors');

colors.enable()

console.log('Error!'.underline.red);
console.log('Warning!'.red);
console.log('This is okay!'.green);

Now update the scripts section in the package.json file by replacing the code with:

 "scripts": {
    "start": "node console.js"
  },

We can test our app and see Chalk in action:

npm start

And the output of this is:

Using Colors.js To Change Colors In Node.js

It’s nifty to be able to call these functions directly on a string, but the fact is that this package pollutes the String implementation in JavaScript.

After all, having .red right next to .indexOf feels wrong, and using a package that modifies the functionality of something as basic as String seems like a scary proposition. It also has been shown to cause issues, so use it with caution (or maybe don’t use it at all).

However, the color.js package provides an alternative module and API which does not extend the String.prototype.

You can use this API by importing the colorjs package from the safe module as seen below:

var colors = require('colors/safe');

console.log(colors.green('hello')); // outputs green text
console.log(colors.red.underline('i like cake and pies')); // outputs red underlined text
console.log(colors.inverse('inverse the color')); // inverses the color
console.log(colors.rainbow('OMG Rainbows!')); // rainbow
console.log(colors.trap('Run the trap')); // Drops the bass

You can replace the code in the console.js file with the code above.
Now to see it working run:

npm start

And we get:

Colors.js Final Product

Lastly, it is important to note that a recent version of Color.js was corrupted and the library was reverted to its previous version of 1.4.0. So use this library with caution (or maybe don’t use it at all).

CLI-Color

Our third option for coloring our console comes in the form of CLI-Color. It has a lot in common with Chalk because it doesn’t modify the String.prototype implementation.

It was last updated on the 16th of October, so it’s still actively maintained.

To use Colors.js create a project directory and from the project directory initialize a Nodejs project by running:

npm init -y

And install color-cli by running:

npm install cli-color

Now create a console.js file inside the project directory with the following code:

var clc = require("cli-color");

console.log(clc.red.underline("Error!"));
console.log(clc.red("Warning!"));
console.log(clc.green('This is okay!'));

Update the scripts section in the package.json file by replacing the code with:

 "scripts": {
    "start": "node console.js"
  },

We can test our app by running:

npm start

And our output looks like this:

Using CLI-Color To Color Your Console

Conclusion

Coloring your console within Node.js is an easy way to make your apps’ outputs more readable. You’re not short on options when it comes to accomplishing this, but if you want to implement this with a package, it seems like Chalk is the most up-to-date, comprehensive option.

Happy coloring! 🎨

200’s only Monitor failed and slow network requests in production

Deploying a Node-based web app or website is the easy part. Making sure your Node instance continues to serve resources to your app is where things get tougher. If you’re interested in ensuring requests to the backend or third party services are successful, try LogRocket. https://logrocket.com/signup/

LogRocket is like a DVR for web and mobile apps, recording literally everything that happens while a user interacts with your app. Instead of guessing why problems happen, you can aggregate and report on problematic network requests to quickly understand the root cause.

LogRocket instruments your app to record baseline performance timings such as page load time, time to first byte, slow network requests, and also logs Redux, NgRx, and Vuex actions/state. .
Lewis Cianci I'm a passionate mobile-first developer, and I've been making apps with Flutter since it first released. I also use ASP.NET 5 for web. Given the chance, I'll talk to you for far too long about why I love Flutter so much.

3 Replies to “Using console colors with Node.js”

  1. Hi, thanks for the good article, some good alternatives for color.js

    You should maybe give a hint, that color.js is not longer usable and can not be used anymore, because it was destroyed by the maintainer.

Leave a Reply