We've all seen a module or a node.js application that has changed the color of the command prompt font. Heck, even npm changes the color of it's text!
I will show you how to do it.
There are two ways of doing this:
- Using a module
- Not using a module
The easy way (with module)
You can go ahead and grab chalk:
npm install chalk
Using chalk is easy! For example, if you want to console.log with blue, then do this:
const chalk = require('chalk'); console.log(chalk.blue('Hello world!'));
Easy, isn't it?
For more documentation, visit the guide.
The not-so-easy way (without a module)
Wanna crank down that dependency list? Noone wants to see code that has too many requires! Go ahead, follow me.
This is a bit messy, but this is basically what the other modules do:
Yes, that long string does the coloring. Here is an explanation:
The "\x1b[36m" part makes your text cyan, the "%s" part gets replaced with your text, and the "\x1b[0m" part resets the colors the way they should be.
But don't worry, you don't have to memorize the color codes. Instead, here is a reference!
Reset = "\x1b[0m" Bright = "\x1b[1m" Dim = "\x1b[2m" Underscore = "\x1b[4m" Blink = "\x1b[5m" Reverse = "\x1b[7m" Hidden = "\x1b[8m" FgBlack = "\x1b[30m" FgRed = "\x1b[31m" FgGreen = "\x1b[32m" FgYellow = "\x1b[33m" FgBlue = "\x1b[34m" FgMagenta = "\x1b[35m" FgCyan = "\x1b[36m" FgWhite = "\x1b[37m" BgBlack = "\x1b[40m" BgRed = "\x1b[41m" BgGreen = "\x1b[42m" BgYellow = "\x1b[43m" BgBlue = "\x1b[44m" BgMagenta = "\x1b[45m" BgCyan = "\x1b[46m" BgWhite = "\x1b[47m"
Hope this tutorial helped someone out there. Thanks for reading!
Top comments (6)
I've found it's useful to honour (or should that be honor?) the
NODE_DISABLE_COLORS
environment variable so users can easily disable this feature if it's not wanted. Documentation here.I simply define colours as:
`
Nice addition!
So it uses ANSI sequences? Sweet. Does it support more than just the color codes?
Yes! There is an article about text positioning coming out very soon.
FWIW, I am working on a node.js version of sixteencolors.net
Posted the position article if you're interested.