Displaying an entire object with Node.js

For the most part, I do the majority of my debugging with Node.js / JavaScript’s
console.log(). It’s quick and dirty but it gets me what I’m looking for.

The exception being when I am working with larger objects, specifically any
object that is nested three or more levels deep. Here’s what I’m referring to:

const myDeepObject = {
  one: {
    two: {
      three: {
        four: {
          five: {
            six: 'too too deep',

If we try to console.log this deep object, we’ll end up being greeted with
everybody’s good friend [Object]:

{ one: { two: { three: [Object] } } }

Not great at all. Fortunately, I tend to work with shallow objects most of the
time. Unfortunately, because of that, I usually forget how to display the
entirety of an object and have to look things up.

At one point, the solution was to bring util to the party and use
util.inspect() but it’s not nearly as elegant with needing an extra import and
all of that.

Turns out, console has a method called dir which takes similar syntax as
util.inspect() with regard to setting the depth limit when displaying an
object (or no limit, as we’re about to see):

console.dir(myDeepObject, { depth: null 

and we get:

  one: {
    two: {
      three: { four: { five: { six: 'too too deep' } } }
Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.

If you found this article helpful, please consider buying me a coffee.