Back

NodeJS: How To Colorize Text

Intro

So we installed NodeJS on our machine.

We also know How to Get External Packages.

Now we want to learn how to colorize text using chalk.

Write a simple script

  • Open your terminal
  • Create a file named index.js:
touch index.js
  • Add this JavaScript code into it:
// import chalk
const chalk = require("chalk");

// Example 1: inline styling, blue background and underline
console.log(chalk.bgBlue.underline("Example 1"));

// Example 2: create reusable style
const success = chalk.bgGreen.black.underline;
console.log(success("Example 2"));

// Example 3: you can do a lot of stuff, e.g. using hex values and template literals
const customize = chalk.hex("#B4DA55").bold;
console.log(`This is ${customize("Example 3")}.`);

Note: Chalk has a lot of available styles, read the docs of chalk.


Run it from the terminal

  • Run it:
node index.js
  • Result:

Alt Text


Further Reading


Questions

  • What is your favorite way/package to colorize text in Node? Why do you use it?