After failing my google on how to crease a strict mode complaint way to do colors in the console/terminal, I finally solved the problem and hope to share my method with the rest of the internet.
Coloring it the ANSI way!
First, look at the ANSI escape code list, and find the exact effect that you want. Remember the code. Next, put it in your
console.log(), and don’t forget the reset it after you’re done!
var red, blue, reset; red = '\033[31m'; blue = '\033[34m'; reset = '\033[0m'; console.log(red + 'This is red' + reset + ' while ' + blue + ' this is blue' + reset);
The above, when run in the terminal, will give you:
So there you have it, using ANSI escape codes to color your output in the terminal.
Strict mode “fix”
But wait! What happens when you add a “use strict” to your file? If you’re like me, who tries to code everything in strict mode, then you’ll run into this error message when you try to run your code:
SyntaxError: Octal literals are not allowed in strict mode.
This is because the “\0″ escape is no longer allowed under strict mode. So what do you do now?
Well, the solution is surprisingly simple. Just replace “\033″ with “\u001b” instead:
'use strict'; var red, blue, reset; red = '\u001b[31m'; blue = '\u001b[34m'; reset = '\u001b[0m'; console.log(red + 'This is red' + reset + ' while ' + blue + ' this is blue' + reset);
And your problems will go away. For your information, “\u” is a unicode escape sequence, and “001b” in unicode is equivalent to your escape character. But I am not really sure on this part – I just know the solution, but the exact explanation evades me.
After asking this question on the Malaysian NodeHack Group, I got a pretty detailed reply from Mats Engstorm:
Octal literals can be identified by a numeric value starting with a leading 0 (zero). Since this is a source of a possible unintentional octal values when the programmer zero-pads decimal numbers of varying lengths in the source code to make then look prettier and more uniform. The strict mode disallows the octal mode due to this reason.
The ESCape code can be represented in a number of ways. Decimal 27 , Hexadecimal 1B , Octal 33 or Binary 00011011.
So instead of write the ESC code in a string as
\033you can as well just choose one of the other modes. Hexadecimal for instance:
In your example you used the two-byte unicode representation of the character
\u001bwhich works just as well.
I’m still an oldschool C head and usually assumes all strings to be plain ASCII so I’d use
\x1Bby default instead of this newfangled unicode crap Java is using. ^_^
Finally, doing ANSI console colors all by yourself is quite tedious, and there are already a few NPM modules out there that’s designed to make your life easier. Go search in the NPM repo for one that suits you. Personally I recommend these modules:
Do share if you are using a different ANSI coloring module!