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.
Written by Dan
Related protips
7 Responses
FYI - the npm colors package is amazing for this.
over 1 year ago
·
Wow, that is so cool! Thanks a lot for sharing!
over 1 year ago
·
[
[ '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
·
How to get this working on Heroku logs (heroku logs) CLI?
over 1 year ago
·
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);
}
over 1 year ago
·
Thanks, this was so useful, so I created my own colors module based upon your observations. https://www.npmjs.com/package/styleme
over 1 year ago
·
Here's my contribution
function colorTextLog(text, color) {
return `\x1b[${color}m${text}\x1b[0m`;
}
// Test logging specific words
console.log(`Hi, I'm ${colorTextLog('cyan color', '36')}!`);
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Node
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#