LEARNNode CLI Automation

Chalk npm CLI Colors for Node.js

A good and appealing user interface is extremely important if you want your CLI to be a success. An easy way of having one is adding colors to your current interface. In command-line tools, you can add colors with a package called chalk.

Let’s take a look at how we can use it in our CLI.

Chalk

You would need to install it first in your project. You can do that by running the following command inside your terminal.

npm install chalk

Usage

Now you would need to require it and then use it. For instance, if you want a green color for the font instead of the traditional white color, you can easily do that with chalk.

const chalk = require('chalk');
console.log(chalk.green('NodeCLI.com'));

This will print a green NodeCLI.com string on your terminal.

Now if you are interested in having a nice background color behind your text, chalk lets you do that as well.

console.log(chalk.bgGreen(chalk.black(`NodeCLI.com`)));

If you carefully take a look at the code, I am first adding a background color and then black font color to our string NodeCLI.com.

chalk background color

Hex Colors

The chalk package also allows you to use hex colors instead of the traditional colors. For instance, if I am interested in using #68a063 as my background, I can easily do that with the following piece of code:

console.log(chalk.hex(`#68a063`).inverse(`NodeCLI.com`));

The inverse function will change the color that is supposed to be for the font to the background. You can read all of its documentation here to get a more clear understanding.

Wrapping Up

You can make all sorts of different color combinations with chalk. It is also a cross-platform package. It means your CLI will still have colors if it runs on other operating systems like Windows. You should definitely give it a shot to improve your CLI user interface.

Posted by Saad (It's a work in progress: Needs copy editing review by Awais.)