How to log entire JavaScript object in Node.js REPL


Problem

Given we have the POJO (Plain Old JavaScript Object):

const obj = {
  1: {
    2: {
      3: {
        4: {}
      }
    }
  }
};

When you log the object (in Node.js):

console.log(obj);

You get the following:

{ '1': { '2': { '3': [Object] } } }

What happened to { 4: {} }?

Node.js formats console.log output with util.inspect so deeply nested objects are replaced with [Object]:

node
> const obj = { 1: { 2: { 3: { 4: {} } } } };
> util.inspect(obj);
'{ \'1\': { \'2\': { \'3\': [Object] } } }'

So how can we log the entire object?

Solution

util.inspect

With util.inspect, you can recurse through the entire object by setting the option depth to null:

const util = require('util');
console.log(util.inspect(obj, { depth: null }));
node index.js
{ '1': { '2': { '3': { '4': {} } } } }

console.dir

Alternatively, the same thing can be accomplished with console.dir:

console.dir(obj, { depth: null });

JSON.stringify

Lastly, you can always fallback to JSON.stringify:

console.log(JSON.stringify(obj, null, 2));
{
  "1": {
    "2": {
      "3": {
        "4": {}
      }
    }
  }
}

The only disadvantage of JSON.stringify is that it doesn’t handle circular references well:

const obj = {};
obj['1'] = obj;
JSON.stringify(obj);
TypeError: Converting circular structure to JSON
    at JSON.stringify (<anonymous>)


Please support this site and join our Discord!