
NodeJS: Using console.dir() over console.log() with deeply nested objects.
console.dir()
seems rather redundant. At least with console.log()
, you can add as many arguments as you want, but with console.dir()
, you can only log one.
Despite that, for debugging, I'll be using console.dir()
more in future. Here's why?
Let's take a deeply nested object.
let hello = { world: true, nested: { obj: { with: "some text", and: { numbers: { count: [1,2,3,4,5,6,7,8,9,10], symbol: Symbol("1"), } } } }}
console.log() to debug
Now, if you do a pure console.log
:
You'll be missing some of the properties that are past a certain depth.
The output is on a single line and not structured in an easily readable way.
# console.log(hello){ world: true, nested: { obj: { with: 'some text', and: [Object] } } }
console.log() to get the whole object
How I'd normally get around expanding that [Object]
is using trusty old JSON.stringify
. And voila 🎉! We have the entire object displayed.
# console.log(JSON.stringify(hello)){"world":true,"nested":{"obj":{"with":"some text","and":{"numbers":{"count":[1,2,3,4,5,6,7,8,9,10]}}}}}
console.log() but pretty
While we could see the entire object before, it's not easy to read. We can fix that by using the JSON.stringify
formatting argument:
# console.log(JSON.stringify(hello, null, 2)){ "world": true, "nested": { "obj": { "with": "some text", "and": { "numbers": { "count": [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] } } } }}
And this is much better, but it still isn't great. Look at that array! That's equally impractical.
console.dir() for better readability
Now, compare all that hard work with console.dir
. You have to add the depth you want to be printed to get the entire object out.
console.dir(hello, { depth: 99 })
And it looks like this:
{ world: true, nested: { obj: { with: 'some text', and: { numbers: { count: [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ], symbol: Symbol(1) } } } }}
It has nice terminal colours because it's not JSON
. It's Javascript! It benefits from the conciseness of javascript and is more compact and yet more readable.
Getting a little more out console.dir()
There are three options you can pass into the formatting argument with console.dir()
. We've already covered depth
so we'll skip that.
console.dir(hello, { showHidden: true, depth: 99, colors: true})
showHidden
allows you to see Javascript annotations such as the length of an array.
{ ... count: [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, [length]: 10 ], ...}
colors
by default istrue
(for me) in the terminal, but you can turn it off if you want. I find the colouring helpful though:
https://cdn.hashnode.com/res/hashnode/image/upload/v1707240290099/67a944d1-ea38-459b-b8d5-595c34a833d8.png" alt class="image--center mx-auto" />
There's nothing more to say really. As I'm reading the Nodejs and finding little gems to make life a little easier. Maybe it's helpful to you.