node: how to print objects

2022-07-06

 | 

~1 min read

 | 

125 words

Previously, I wrote about using JSON.stringify to pretty print objects. Unfortunately, there’s a limitation: objects with circular references. This is actually more common than I initially thought as HTML elements and AJAX responses are circular.

Fortunately, there’s an alternative in Node environments: the utils module’s inspect method.

const util = require("util")
const obj = { a: { b: { c: 1, d: 2 } } }
console.log(util.inspect(obj, { depth: null, colors: true }))
{ a: { b: { c: 1, d: 2 } } }
console.log(util.inspect(obj, { depth: null, colors: true, compact: false }))
{
  a: {
    b: {
      c: 1,
      d: 2
    }
  }
}

The full suite of options is available in the Node.js docs.



Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!