Node.js: 2 Ways to Colorize Console Log Output
( 30 Articles)
By default, when you print something by using console.log() in Node.js, the output is usually white if your terminal has a dark background color or black if your terminal has a light background color. If you print a few short messages using console.log(), there will be nothing to worry about. However, when you print some long text, it may become a mess and hard to read.
This article shows you 2 techniques to colorize your console log output messages. The first one is to use self-written code and the second one it to use a third-party library.
Using self-written code
For example, we’ll create a file called index.js and put into it some code like this:
// red console.log('\x1b[31m%s\x1b[0m', 'I am red') // green console.log('\x1b[32m%s\x1b[0m', 'I am green') // yellow console.log('\x1b[33m%s\x1b[0m', 'I am yellow') // blue console.log('\x1b[34m%s\x1b[0m', 'I am blue') // magenta console.log('\x1b[35m%s\x1b[0m', 'I am magenta') // cyan console.log('\x1b[36m%s\x1b[0m', 'I am cyan')
Execute the code by typing the following command in the terminal window:
An here is the result:
Using a third-party package
Using a package saves you from having to remember the syntax as the first method. There are many famous names that meet our needs such as colors, chalk, etc. The example below will use the colors library.
npm i colors
const colors = require('colors'); console.log('Blue Kindacode.com'.blue); console.log('This is a yellow sentence'.yellow); console.log('This is green'.green); console.log('Random color'.random); console.log('Bright blue'.brightBlue); console.log('Bright Red'.brightRed);
Below is the list of colors supported by the library:
To explore more options, see the official docs.
We have walked through 2 approaches to colorize console messages in Node.js. From now on, you will get a nicer experience when developing and debugging applications. If you would like to explore more things about Node.js and related stuff, take a look at the following articles:
- Using Axios to download images and videos in Node.js
- Node.js: Get File Name and Extension from Path/URL
- Top 4 best Node.js Open Source Headless CMS
- How to get all Links from a Webpage using Node.js and Cheerio
You can also check out our Node.js category page for the latest tutorials and examples.