How can I get the full object in Node.js's console.log(), rather than '[Object]'?
Solution 1
You need to use util.inspect()
:
const util = require('util')
console.log(util.inspect(myObject, {showHidden: false, depth: null, colors: true}))
// 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
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). Tip of the hat to Rory O'Kane for his help.
tl;dr
To get the desired output for the example in the question, use console.dir()
:
console.dir(myObject, { depth: null }); // `depth: null` ensures unlimited recursion
Why not util.inspect()
? Because it’s already at the heart of diagnostic output: console.log()
and console.dir()
as well as the Node.js REPL use util.inspect()
implicitly. It’s generally not necessary to require('util')
and call util.inspect()
directly.
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 useconsole.dir()
:console.dir(myObject, { depth: null }
prints with unlimited depth; see below.
- Since you cannot change this with
- You can’t turn syntax coloring on.
- Structural depth of the output is limited to 2 levels (the default).
-
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.
- There is NO placeholder for representing objects
-
If the 1st argument is NOT a format string:
-
-
Accepts only 1 argument to inspect, and always applies
util.inspect()
– essentially, a wrapper forutil.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.
-
Accepts only 1 argument to inspect, and always applies
-
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(){} } // The REPL echoes the object definition with syntax coloring.
util.inspect()
automatically pretty-prints object and array representations, but produces multiline output only when needed.
The pretty-printing behavior can be controlled by the
compact
property in the optionaloptions
argument;false
uses multi-line output unconditionally, whereastrue
disables pretty-printing altogether; it can also be set to a number (the default is3
) to control the conditional multi-line behavior – see the docs.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 toInfinity
, 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):
An optional options object may be passed that alters certain aspects of the formatted string; some of the properties supported are:
See the latest Node.js docs for the current, full list.
-
showHidden
- if
true
, then the object's non-enumerable properties [those designated not to show up when you usefor keys in obj
orObject.keys(obj)
] will be shown too. Defaults tofalse
.
- if
-
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
.
- 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
-
colors
- if true, then the output will be styled with ANSI color codes. Defaults to
false
. Colors are customizable [… – see link].
- if true, then the output will be styled with ANSI color codes. Defaults to
-
customInspect
- if
false
, then custominspect()
functions defined on the objects being inspected won't be called. Defaults totrue
.
- if
util.format()
format-string placeholders (1st argument)
Some of the supported placeholders are:
See the latest Node.js docs for the current, full list.
-
%s
– String. -
%d
– Number (both integer and float). -
%j
– JSON. -
%%
– single percent sign (‘%’). This does not consume an argument.
Solution 3
Another simple method is to convert it to json
console.log('connection : %j', myObject);
Solution 4
Since Node.js 6.4.0, this can be elegantly solved with util.inspect.defaultOptions
:
require("util").inspect.defaultOptions.depth = null;
console.log(myObject);
Solution 5
Try this:
console.dir(myObject,{depth:null})
Admin
Updated on July 08, 2022Comments
-
Admin almost 2 years
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
. -
Dan Dascalescu almost 10 yearsNice trick but the output won't be prettified, which makes it hard to read for large objects (the point of the question).
-
Dan Dascalescu almost 10 years
-
ecdeveloper over 9 yearsNice solution. Though no need to specify {showHidden: false} as long as it defaults to false.
-
mklement0 over 9 yearsAs of (at least) v0.11.14, you can pass an options object as the 2nd argument, which is passed to
util.inspect()
. -
mklement0 over 9 yearsGood to know; not sure when it was introduced, but as of at least node
v0.10.33
console.log()
implicitly appliesutil.inspect()
to its arguments, assuming the 1st one is not a format string. If you're happy withutil.inspect()
's default options, simplyconsole.log(myObject)
will do - no need to requireutil
;console.dir()
does the same, but accepts only ` object to inspect; as of at leastv0.11.14
, you can pass the options object forutil.inspect()
as the 2nd argument; my answer has more details. -
mklement0 about 9 yearsCorrection to my previous comment: "
console.dir()
does the same, but accepts only ` object to inspect" should have been "... accepts only one object to inspect". -
sebilasse almost 9 yearsIf you need it for "generators" and use the output in code: Be careful: It seems util.inspect doesn't quote sensitive Object.keys. Tested with {in: 'i'}
-
SSH This about 8 years@mklement0 I have node v5.3.0 and when I
console.log(obj)
it still prints [Object] for deeply nested objects :( I really wish it would behave as you describe. -
SSH This about 8 yearsstill very useful, and quicker to copy and paste into jsonlint.com than requiring
utils
:) -
mklement0 about 8 years@SSH:
console.log()
is invariably limited to 2 levels (because it usesutil.inspect()
's default without allowing you to change it);console.dir()
has the same limit by default, but you can pass in an options object as the 2nd argument to change that (which is passed through toutil.inspect()
; note thatconsole.dir()
can only ever print 1 object at a time, however. To print with unlimited depth, useconsole.dir(myObject, { depth: null })
. -
neoDev about 8 yearsHow can I console.log() it into client console making it collapsible? I mean the fold/unfold feature to open close its children
-
loretoparisi over 7 yearsdefinitively
util.inspect
is the right solution. See here for all options, styles and colors as well! nodejs.org/api/util.html#util_util_inspect_object_options -
Veck Hsiao about 7 years
console.dir(myObject, { depth: null })
is work for me -
Chintan over 6 years@Bala You will need to install "debug" module in your project "npm install debug --save"
-
jcollum over 6 yearsI think this one is great when you have an editor that will format json for you but you just need to copy it out from REPL
-
Jason Goemaat about 6 years@VeckHsiao has the best comment, and it is in the community answer below.
console.dir(myObject, { depth: 4, colors: true }
for instance is what I use. Easier thanutil.inspect
and has the same output with keeping small objects/arrays on one line and providing class names, function references with their names, etc), and syntax highlighting... -
Chinmay Samant over 5 yearsThis is very handy and helpful if the object is small
-
Lonely about 5 yearsA message for me: try that out ->
node.exe --inspect index.js
-
Gershom Maes over 4 yearsThis doesn't solve the problem of printing
myObject
to an arbitrary depth -
LordParsley about 4 yearsThis is a great one for AWS CloudWatch which tends to break console.dir and other loggers into individual lines, which it doesn't do for console.log.
-
princebillyGK about 4 yearsThis should be on top. best answer. :)
-
loco.loop about 4 yearsOne way to simplify this would be to do a small named function to do
console.dir(...)
without all the typing:show = (v, depth=null)=> console.dir(v,{depth:depth})
and then call it like soshow(variable)
orshow(variable, depth=1)
. -
Dan Dascalescu almost 4 years@VeckHsiao:
console.dir(mongooseObject, { depth: null })
prints far less thanconsole.log(util.inspect(mongooseObject, {depth: null}))
, so they're not always equivalent. -
Deunz about 3 yearsThanks for this complete answer => THE BEST SOLUTION YOU GAVE : JSON.stringify({ one: 1, two: 'deux', three: true}, undefined, 2);
-
jpoppe about 2 yearsAlso works with
console.dir
. -
Gel almost 2 yearstoday 2022, I tried to use
console.dir
with thebrackets {yourObjHere}
like soconsole.dir({yourObjectHere},{depth:null})
it created an object and made its format a little easier on the eyes.