Node.js: Colorizing console.log() output without third-party libraries

Last updated on April 4, 2021 A Goodman Loading... One comment

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.

For example, we’ll create a file called index.js and put into it some code like this:

// red
console.log('\x1b[31m', 'I am red')

// green
console.log('\x1b[32m', 'I am green')

// yellow
console.log('\x1b[33m', 'I am yellow')

// blue
console.log('\x1b[34m', 'I am blue')

// magenta
console.log('\x1b[35m', 'I am magenta')

// cyan
console.log('\x1b[36m', 'I am cyan')

Execute the code by typing the following command in the terminal window (If using Visual Studio Code, you can open the terminal by pressing ctrl + ~):

node index.js

An here is the result:

Happy coding 🙂

Related Articles

1 Comment
Newest Most Voted
Inline Feedbacks
View all comments
Express: Automatically download an image when clicking a link | Kindacode
11 months ago

[…] See also: Colorizing the console log output in Node […]

Would love your thoughts, please comment.x