DEV Community

loading...

NodeJS: How To Colorize Text

miku86 profile image miku86 Updated on ・1 min read

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
Enter fullscreen mode Exit fullscreen mode
  • 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')}.`);
Enter fullscreen mode Exit fullscreen mode

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


Run it from the terminal

  • Run it:
node index.js
Enter fullscreen mode Exit fullscreen mode
  • Result:

Alt Text


Further Reading


Questions

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

Discussion (3)

pic
Editor guide
Collapse
talentlessguy profile image
v 1 r t l

My favourite way is escaping symbols instead of downloading a pkg to get extra free mb.

Example:

const reset = '\x1b[0m'

export const blue = msg => `\x1b[34m${msg}${reset}`

export const cyan = msg => `\x1b[36m${msg}${reset}`

export const bold = msg => `\x1b[1m${msg}${reset}`

Source: github.com/talentlessguy/f-serv/bl...

Collapse
avasconcelos114 profile image
Andre Vasconcelos

I recently used the same thing to have color-coded logging on my node app :)

looks a little something like this:

function debug(message) {
    const timestamp = new Date().toString()
    console.log('\x1b[36m%s\x1b[0m', `${timestamp} - ${message}`)
}

function error(message) {
    const timestamp = new Date().toString()
    console.error('\x1b[31m%s\x1b[0m', `${timestamp} - ${message}`)
}
Collapse
miku86 profile image
miku86 Author

Hey v 1 r t l & Andre,

thanks for your tips,
I will have a look at it.

If anyone is interested in further information:
various escape codes
bigger discussion on stackoverflow