Bisexual Pride

Have you ever tried to inspect a deeply nested object in Node.js, only to be frustrated by the compact output?

Take this array of restaurants:

const restaurants = [
{
name: 'Nando\'s',
menus: {
starters: [
{ name: 'Halloumi Sticks & Dip', price: 425 },
{ name: 'Houmous with PERi-PERi Drizzle', price: 425 },
{ name: 'Sweet Potato Wedges with Garlic PERinaise', price: 425 }
],
mains: [
{ name: '1/4 Chicken', price: 425 },
{ name: '1/2 Chicken', price: 795 },
{ name: 'Whole Chicken', price: 1450 }
],
desserts: [
{ name: 'Choc-A-Lot Cake', price: 475 },
{ name: 'Naughty Nata', price: 195 },
{ name: 'Bottomless Frozen Yoghurt', price: 295 }
]
}
}
];

If we invoke console.log(restaurants), this is the output we see in the console:

[
{
name: "Nando's",
menus: { starters: [Array], mains: [Array], desserts: [Array] }
}
]

What if we want to see the values inside the nested arrays?

The util.inspect() method

Enter the util.inspect() method!

Here’s the official description of the util module:

The util module supports the needs of Node.js internal APIs. Many of the utilities are useful for application and module developers as well.

And the util.inspect() method:

The util.inspect() method returns a string representation of object that is intended for debugging.

Here’s how we might use it, with my recommended options:

const { inspect } = require('util');

console.log(inspect(restaurants, {
depth: Infinity, // Recurse up to the maximum call stack size.
colors: true, // Style the output with ANSI color codes.
compact: false // Display each object key on a new line.
}));

And here’s the nicely formatted output:

[
{
name: "Nando's",
menus: {
starters: [
{
name: 'Halloumi Sticks & Dip',
price: 425
},
{
name: 'Houmous with PERi-PERi Drizzle',
price: 425
},
{
name: 'Sweet Potato Wedges with Garlic PERinaise',
price: 425
}
],
mains: [
{
name: '1/4 Chicken',
price: 425
},
{
name: '1/2 Chicken',
price: 795
},
{
name: 'Whole Chicken',
price: 1450
}
],
desserts: [
{
name: 'Choc-A-Lot Cake',
price: 475
},
{
name: 'Naughty Nata',
price: 195
},
{
name: 'Bottomless Frozen Yoghurt',
price: 295
}
]
}
}
]

For more formatting options, check the official documentation. I’ve put the code from this blog post in a Gist for your convenience.