Search code examples
javascriptnode.jsvisual-studio-codeconsole.logansi-escape

How to console.log objects as a color?


(node.js) if i try to color an object on console.log like so

console.log('\x1b[32m', {a:1,b:2,c:3}, '\x1b[0m');

it looks like this:

enter image description here

how do I make it so the text actually all gets colored?

I know i could stringify the arguments manually then join them to a single string and color them, but that ruins the nice multiline formatting console.log usually employs:

enter image description here


Solution

  • In order to convert an object to a pretty json string you may pass a 3rd param as the indent size for beautify-ing the input.

    var obj = {
      some: "thing",
      values: {
        arr: [12, 15, 24],
        size: null
      }
    }
    
    console.log("this is a string: " + JSON.stringify(obj, null, 4))

    Then of course you can colorize it using one color. See comments above for techniques.