
chalk is a JavaScript library for styling the console output strings in a terminal. We can style using foreground and background colors, Underline, Bold and RGB colors.
It is a popular library used in Nodejs to apply syntax colors to
features
- Opensource
- npm library provided
- All colors are supported
- Server-side support, not a browser-based library
Let’s first create a node application called chalkjsdemo
.
First create a chalkjsdemo
directory
mkdir chalkjsdemo
cd chalkjsdemo
next, run npm init -y command
to initialize node application in this folder
npm init -y
It creates a package.json file in the application root directory.
next, install the chalkjs library using the npm install command
npm I chalk
This adds an entry in package.json and installs dependency to node_modules of your application.
Create a main.js file, add the following lines of chalkjs code
main.js
const chalk = require('chalk');
console.log(chalk.red('Hello World'));
console.log(chalk.green('Welcome to ') + ' chalkjs' + chalk.yellow(' Application'));
And the console output in terminal is
See how the console strings are colored and It looks like visual studio code syntax.
This way we can add syntax colors to console output strings in nodejs applications like angular, react, and vuejs.
In this example, We added font colors and background color styles to strings.
It has support for a complete set of palette colors as seen below.
following are colors supported
foreground color | background color |
---|---|
red | bgRed |
green | bgGreen |
Adding bold, underline, and Italic styles to terminal console string
It is very easy to add bold to console strings.
In the same way, we can add underline, Italic to console strings.
console.log(
chalk.underline.bold('Chalkjs terminal example styles')
);
console.log(
chalk.green.underline.bold('Chalkjs terminal example styles')
);
console.log(
chalk.green.bgRed.underline.bold('Chalkjs terminal styles')
);