yphywg
Last Updated: January 16, 2017
·
18.14K
· aladine
Ac36fd1db0498ad7ff61442fe5f9d721

Printing colorful text in terminal when run node js script

You can print colorful text to command when run nodejs application.

console.log('\x1b[36m%s\x1b[0m', info);  //cyan
console.log('\x1b[33m%s\x1b[0m: ', path);  //yellow

Here is reference of colors and other characters:

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"

P/s: I am using terminal in Mac OS.

6 Responses
Add your response

12440
D3b2094f1b3386e660bb737e797f5dcc

FYI - the npm colors package is amazing for this.

screenshot

over 1 year ago ·
15891

Wow, that is so cool! Thanks a lot for sharing!

over 1 year ago ·
18334
00e0edf55714e9903e421d6ae0da19dc
[
 [ 'warn',  '\x1b[35m' ],
 [ 'error', '\x1b[31m' ],
 [ 'log',   '\x1b[2m'  ]
].forEach(function(pair) {
  var method = pair[0], reset = '\x1b[0m', color = '\x1b[36m' + pair[1];
  console[method] = console[method].bind(console, color, method.toUpperCase(), reset);
});
over 1 year ago ·
18740
Eacf0fe0d603c05cf185900f66a95abd

How to get this working on Heroku logs (heroku logs) CLI?

over 1 year ago ·
26576
0cb9bbba22c045d3b178306407408cc8

Thx a lot!
I've used it to make my logs look better:

/**
 * Does console.log and formats the data a nice way
 * @param {any[]} ...args
 */
function log() {
    var args = Array.prototype.slice.call(arguments);
    var logToWrite = args.map(function (arg) {
        var str;
        var argType = typeof arg;

        if (arg === null) {
            str = 'null';
        } else if (arg === undefined) {
            str = '';
        } else if (!arg.toString || arg.toString() === '[object Object]') {
            str = JSON.stringify(arg, null, '  ');
        } else if (argType === 'string') {
            str = '"' + arg.toString() + '"';
        } else {
            str = arg.toString();
        }

        return '\x1b[36m<\x1b[0m' + str + '\x1b[36m>\x1b[0m';
    }).join(', ');
    console.log(logToWrite);
}
12 months ago ·
28502

Thanks, this was so useful, so I created my own colors module based upon your observations. https://www.npmjs.com/package/styleme

7 days ago ·