如何获得 Node.js 的 console.log ()中的完整对象,而不是"[ 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.

转载于:https://stackoverflow.com/questions/10729276/how-can-i-get-the-full-object-in-node-jss-console-log-rather-than-object

14个回答

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.

csdnceshi62
csdnceshi62 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 than util.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...
2 年多之前 回复
csdnceshi55
~Onlooker you're a life saver. great tip!
大约 3 年之前 回复
csdnceshi78
程序go console.dir(myObject, { depth: null }) is work for me
3 年多之前 回复
csdnceshi70
笑故挽风 definitively 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
接近 4 年之前 回复
csdnceshi63
elliott.david How can I console.log() it into client console making it collapsible? I mean the fold/unfold feature to open close its children
4 年多之前 回复
csdnceshi64
游.程 console.log() is invariably limited to 2 levels (because it uses util.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 to util.inspect(); note that console.dir() can only ever print 1 object at a time, however. To print with unlimited depth, use console.dir(myObject, { depth: null }).
4 年多之前 回复
csdnceshi77
狐狸.fox 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.
4 年多之前 回复
csdnceshi65
larry*wei This is awesome!
大约 5 年之前 回复
csdnceshi67
bug^君 If 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'}
5 年多之前 回复
csdnceshi64
游.程 Correction to my previous comment: "console.dir() does the same, but accepts only ` object to inspect" should have been "... accepts only one object to inspect".
5 年多之前 回复
csdnceshi64
游.程 Good to know; not sure when it was introduced, but as of at least node v0.10.33 console.log() implicitly applies util.inspect() to its arguments, assuming the 1st one is not a format string. If you're happy with util.inspect()'s default options, simply console.log(myObject) will do - no need to require util; console.dir() does the same, but accepts only ` object to inspect; as of at least v0.11.14, you can pass the options object for util.inspect() as the 2nd argument; my answer has more details.
接近 6 年之前 回复
weixin_41568184
叼花硬汉 Nice solution. Though no need to specify {showHidden: false} as long as it defaults to false.
接近 6 年之前 回复
weixin_41568134
MAO-EYE Thanks!! I can create helper method to wrap the call to util.inspect()
8 年多之前 回复

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.
weixin_41568127
?yb? Definitely the correct answer!
接近 2 年之前 回复
weixin_41568208
北城已荒凉 bold-facing key parts is not "randomly making things bold" (although what the key parts are is a matter of taste, to a degree). Formatting code elements as such to my mind helps readability.
2 年多之前 回复
weixin_41568208
北城已荒凉 I'm glad you found something useful in it. The "messiness" stems from packing a lot of information into a concise answer, and bold-facing key parts is meant to make locating the important parts easier. How would you make it less messy without sacrificing these goals?
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

csdnceshi62
csdnceshi62 console.log(JSON.stringify(myObject, null, 4)); pretty cool! https://gist.github.com/xgqfrms-GitHub/92aa2b00249f15084d24aa2e0a5d0300
3 年多之前 回复
csdnceshi80
胖鸭 JSON.stringify is ok, but consider that only works on json structures. If you want to output a javascript object, this will not work in all cases, while util.inspect will. Also, to avoid ...more items of console.log you need to pass to util.inspect the { maxArrayLength: 1000 } option, in this case to print up to 1000 items in any case.
接近 4 年之前 回复
csdnceshi65
larry*wei So what's the solution for that situation?
4 年多之前 回复
weixin_41568131
10.24 this isn't the full object. objects containing only functions will be {}. Of course that may be a positive or a negative depending on what you want to print out.
接近 5 年之前 回复
csdnceshi56
lrony* thanks a lot man :)
接近 5 年之前 回复
csdnceshi76
斗士狗 keep in mind that this is not going to show undefined values
5 年多之前 回复
csdnceshi59
ℙℕℤℝ Note that you cannot JSON.stringify objects with circular references. Like it would occur with DOM objects, for example. Stringify will throw an "Error: Converting circular structure to JSON".
6 年多之前 回复
weixin_41568134
MAO-EYE also +1 for line breaks and indentation - almost always desired for me personally
大约 7 年之前 回复
weixin_41568196
撒拉嘿哟木头 +1 for not needing to require anything
7 年多之前 回复
csdnceshi50
三生石@ Ah this is handy too! thanks!
8 年多之前 回复

You can also do

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

A simple trick would be use debug module to add DEBUG_DEPTH=null as environment variable when running the script

Ex.

DEBUG=* DEBUG_DEPTH=null node index.js

In you code

const debug = require('debug');
debug("%O", myObject);
csdnceshi72
谁还没个明天 You will need to install "debug" module in your project "npm install debug --save"
接近 3 年之前 回复
csdnceshi54
hurriedly% Its giving error like "debug is not function"
接近 3 年之前 回复

perhaps console.dir is all you need.

http://nodejs.org/api/console.html#console_console_dir_obj

Uses util.inspect on obj and prints resulting string to stdout.

use util option if you need more control.

csdnceshi63
elliott.david As of (at least) v0.11.14, you can pass an options object as the 2nd argument, which is passed to util.inspect().
接近 6 年之前 回复
csdnceshi55
~Onlooker console.dir is buggy and doesn't yet pass on the options object to util.inspect.
大约 6 年之前 回复

Both of these usages can be applied

// more compact and colour can be applied (better for process managers logging)

console.dir(queryArgs, { depth: null, colors: true });

// clear list of actual values

console.log(JSON.stringify(queryArgs, undefined, 2));

Try this:

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

A good way to inspect objects is to use node --inspect option with Chrome DevTools for Node.

node.exe --inspect www.js

Open chrome://inspect/#devices in chrome and click Open dedicated DevTools for Node

Now every logged object is available in inspector like regular JS running in chrome.

enter image description here

There is no need to reopen inspector, it connects to node automatically as soon as node starts or restarts. Both --inspect and Chrome DevTools for Node may not be available in older versions of Node and Chrome.

The node REPL has a built-in solution for overriding how objects are displayed, see here.

The REPL module internally uses util.inspect(), when printing values. However, util.inspect delegates the call to the object's inspect() function, if it has one.

共14条数据 1 尾页
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐