How can I get the full object in Node.js’s console.log(), rather than ‘[Object]’?

How can I get the full object in Node.js’s console.log(), rather than ‘[Object]’?

When debugging using console.log(), how can I get the full object?
const myObject = {
“a”:”a”,
“b”:{
“c”:”c”,
“d”:{
“e”:”e”,
“f”:{
“g”:”g”,
“h”:{
“i”:”i”
}
}
}
}
};
console.log(myObject);

Outputs:
{ a: ‘a’, b: { c: ‘c’, d: { e: ‘e’, f: [Object] } } }

But I want to also see the content of property f.

Solutions/Answers:

Solution 1:

You need to use util.inspect():

const util = require('util')

console.log(util.inspect(myObject, {showHidden: false, depth: null}))

// alternative shortcut
console.log(util.inspect(myObject, false, null, true /* enable colors */))

Outputs

{ a: 'a',  b: { c: 'c', d: { e: 'e', f: { g: 'g', h: { i: 'i' } } } } }

See util.inspect() docs.

Solution 2:

You can use JSON.stringify, and get some nice indentation as well as perhaps easier to remember syntax.

console.log(JSON.stringify(myObject, null, 4));

{
    "a": "a",
    "b": {
        "c": "c",
        "d": {
            "e": "e",
            "f": {
                "g": "g",
                "h": {
                    "i": "i"
                }
            }
        }
    }
}

The third argument sets the indentation level, so you can adjust that as desired.

More detail here if needed:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

Solution 3:


A compilation of the many useful answers from (at least) Node.js v0.10.33 (stable) / v0.11.14 (unstable) presumably through (at least) v7.7.4 (the version current as of the latest update to this answer).

tl;dr

util.inspect() is at the heart of diagnostic output: console.log() and console.dir() as well as the Node.js REPL use util.inspect() implicitly, so it’s generally not necessary to require('util') and call util.inspect() directly.

To get the desired output for the example in the question:

console.dir(myObject, { depth: null }); // `depth: null` ensures unlimited recursion

Details below.


  • console.log() (and its alias, console.info()):

    • If the 1st argument is NOT a format string: util.inspect() is automatically applied to every argument:
      • o = { one: 1, two: 'deux', foo: function(){} }; console.log(o, [1,2,3]) // -> '{ one: 1, two: 'deux', foo: [Function] } [ 1, 2, 3 ]'
      • Note that you cannot pass options through util.inspect() in this case, which implies 2 notable limitations:
        • Structural depth of the output is limited to 2 levels (the default).
          • Since you cannot change this with console.log(), you must instead use console.dir(): console.dir(myObject, { depth: null } prints with unlimited depth; see below.
        • You can’t turn syntax coloring on.
    • If the 1st argument IS a format string (see below): uses util.format() to print the remaining arguments based on the format string (see below); e.g.:
      • o = { one: 1, two: 'deux', foo: function(){} }; console.log('o as JSON: %j', o) // -> 'o as JSON: {"one":1,"two":"deux"}'
      • Note:
        • There is NO placeholder for representing objects util.inspect()-style.
        • JSON generated with %j is NOT pretty-printed.
  • console.dir():

    • Accepts only 1 argument to inspect, and always applies util.inspect() – essentially, a wrapper for util.inspect() without options by default; e.g.:
      • o = { one: 1, two: 'deux', foo: function(){} }; console.dir(o); // Effectively the same as console.log(o) in this case.
    • node.js v0.11.14+: The optional 2nd argument specifies options for util.inspect() – see below; e.g.:
      • console.dir({ one: 1, two: 'deux'}, { colors: true }); // node 0.11+: Prints object representation with syntax coloring.
  • The REPL: implicitly prints any expression’s return value with util.inspect() with syntax coloring;
    i.e., just typing a variable’s name and hitting Enter will print an inspected version of its value; e.g.:

    • o = { one: 1, two: 'deux', foo: function(){} } // echoes the object definition with syntax coloring.

util.inspect() automatically (and invariably) pretty-prints object and array representations, but produces multiline output only when needed – if everything fits on one line, only 1 line is printed.

  • By default, output is wrapped at around 60 characters thanks, Shrey
    , regardless of whether the output is sent to a file or a terminal. In practice, since line breaks only happen at property boundaries, you will often end up with shorter lines, but they can also be longer (e.g., with long property values).

  • In v6.3.0+ you can use the breakLength option to override the 60-character limit; if you set it to Infinity, everything is output on a single line.

If you want more control over pretty-printing, consider using JSON.stringify() with a 3rd argument, but note the following:

  • Fails with objects that have circular references, such as module in the global context.
  • Methods (functions) will by design NOT be included.
  • You can’t opt into showing hidden (non-enumerable) properties.
  • Example call:
    • JSON.stringify({ one: 1, two: 'deux', three: true}, undefined, 2); // creates a pretty-printed multiline JSON representation indented with 2 spaces

util.inspect() options object (2nd argument):

source: http://nodejs.org/api/util.html#util_util_format_format

An optional options object may be passed that alters certain aspects of the formatted string:

  • showHidden
    • if true, then the object’s non-enumerable properties [those designated not to show up when you use for keys in obj or Object.keys(obj)] will be shown too. Defaults to false.
  • depth
    • tells inspect how many times to recurse while formatting the object. This is useful for inspecting large complicated objects. Defaults to 2. To make it recurse indefinitely, pass null.
  • colors
    • if true, then the output will be styled with ANSI color codes. Defaults to false. Colors are customizable [… – see link].
  • customInspect
    • if false, then custom inspect() functions defined on the objects being inspected won’t be called. Defaults to true.

util.format() format-string placeholders (1st argument)

source: http://nodejs.org/api/util.html#util_util_format_format

  • %s – String.
  • %d – Number (both integer and float).
  • %j – JSON.
  • % – single percent sign (‘%’). This does not consume an argument.

Solution 4:

Another simple method is to convert it to json

console.log('connection : %j', myObject);

Solution 5:

Try this:

console.dir(myObject,{depth:null})

Solution 6:

Since Node.js 6.4.0, this can be elegantly solved with util.inspect.defaultOptions:

require("util").inspect.defaultOptions.depth = null;
console.log(myObject);