⚡ See me talk about this at the London Node User Group ⚡
Found out today that while debugging a node application using console.log()
in the terminal I can pass arguments that formats the styles in the console.
console.log('\x1b[31m', 'Hello, world', '\x1b[0m'); // red
Let's break down what this means though;
\x1b[31m
- This is an ANSI style, the\x1b[
is made up of an escape sequence,\x1b
, and a[
. Together this is called a Control Sequence Introducer (or Initiator). The CSI is followed by31
which is the actual styling (in this case red text) this is then followed bym
which is the ANSI code terminator.- Since you can pass multiple arguments to
console.log
I'm placing what I want to log in the middle. \x1b[0m
- Like the one at the beginning but it uses the styling code0
which will reset the styling. If you don't have this everything in your terminal will be styled until something else overwrites it.
Code | Style |
---|---|
31 |
Red Text |
32 |
Green Text |
33 |
Yellow Text |
34 |
Blue Text |
35 |
Magenta Text |
36 |
Cyan Text |
41 ..46 |
[color as above] Background |
A more complete list can be found here
To use these as snippets in Atom paste the following into your ~/.atom/snippets.cson
'.source.js':
'Console log Red':
'prefix': 'logr'
'body': 'console.log(\'\\\\x1b[31m\', $1, \'\\\\x1b[0m\')'
'Console log Green':
'prefix': 'logg'
'body': 'console.log(\'\\\\x1b[32m\', $1, \'\\\\x1b[0m\')'
'Console log Yellow':
'prefix': 'logy'
'body': 'console.log(\'\\\\x1b[33m\', $1, \'\\\\x1b[0m\')'
'Console log Blue':
'prefix': 'logb'
'body': 'console.log(\'\\\\x1b[34m\', $1, \'\\\\x1b[0m\')'
'Console log Magenta':
'prefix': 'logm'
'body': 'console.log(\'\\\\x1b[35m\', $1, \'\\\\x1b[0m\')'
'Console log Cyan':
'prefix': 'logc'
'body': 'console.log(\'\\\\x1b[36m\', $1, \'\\\\x1b[0m\')'
Paste the following into the Code > Preferences > User Snippets > javascript.json
file
"Console log Red": {
"prefix": "logr",
"body": "console.log('\\x1b[31m', $1, '\\x1b[0m')",
"description": "Log out put to the console in red"
},
"Console log Green": {
"prefix": "logg",
"body": "console.log('\\x1b[32m', $1, '\\x1b[0m')",
"description": "Log out put to the console in green"
},
"Console log Yellow": {
"prefix": "logy",
"body": "console.log('\\x1b[33m', $1, '\\x1b[0m')",
"description": "Log out put to the console in yellow"
},
"Console log Blue": {
"prefix": "logb",
"body": "console.log('\\x1b[34m', $1, '\\x1b[0m')",
"description": "Log out put to the console in blue"
},
"Console log Magenta": {
"prefix": "logm",
"body": "console.log('\\x1b[35m', $1, '\\x1b[0m')",
"description": "Log out put to the console in magenta"
},
"Console log Cyan": {
"prefix": "logc",
"body": "console.log('\\x1b[36m', $1, '\\x1b[0m')",
"description": "Log out put to the console in cyan"
}