Javascript 如何在 Node.js 的 console.log() 中获取完整对象,而不是“[Object]”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10729276/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I get the full object in Node.js's console.log(), rather than '[Object]'?
提问by 250R
When debugging using console.log()
, how can I get the full object?
使用 调试时console.log()
,如何获取完整对象?
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
.
但我也想看看 property 的内容f
。
回答by 250R
You need to use util.inspect()
:
你需要使用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.
请参阅util.inspect()
文档。
回答by 250R
You can use JSON.stringify
, and get some nice indentation as well as perhaps easier to remember syntax.
您可以使用JSON.stringify
, 并获得一些不错的缩进以及可能更容易记住的语法。
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
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
回答by mklement0
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'Kanefor his help.
来自(至少)Node.js v0.10.33
(稳定)/ v0.11.14
(不稳定)的许多有用答案的汇编,大概是通过(至少)v7.7.4
(截至此答案的最新更新的最新版本)。尖帽子的罗里·奥凯恩对他的帮助。
tl;dr
tl;博士
To get the desired output for the example in the question, use console.dir()
:
要获得问题示例所需的输出,请使用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 notnecessary to require('util')
and call util.inspect()
directly.
为什么不util.inspect()
呢?因为它已经在诊断输出的心脏:console.log()
和console.dir()
以及Node.js的REPL使用util.inspect()
隐式。它通常没有必要require('util')
,并调用util.inspect()
直接。
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 optionsthrough
util.inspect()
in this case, which implies 2 notable limitations:- Structural depthof the output is limited to 2levels(the default).
- Since you cannot change this with
console.log()
, you must instead useconsole.dir()
:console.dir(myObject, { depth: null }
prints with unlimiteddepth; see below.
- Since you cannot change this with
- You can't turn syntax coloring on.
- Structural depthof the output is limited to 2levels(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 1argument 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 1argument to inspect, and always applies
console.log()
(及其别名,console.info()
):- 如果第一个参数不是格式字符串:
util.inspect()
自动应用于每个参数:o = { one: 1, two: 'deux', foo: function(){} }; console.log(o, [1,2,3]) // -> '{ one: 1, two: 'deux', foo: [Function] } [ 1, 2, 3 ]'
- 请注意,您无法通过选择通过
util.inspect()
在这种情况下,这意味着2个值得注意的限制:- 输出的结构深度限制为2 个级别(默认)。
- 因为你不能用 改变它
console.log()
,你必须改用console.dir()
:无限深度的console.dir(myObject, { depth: null }
打印;见下文。
- 因为你不能用 改变它
- 您无法打开语法着色。
- 输出的结构深度限制为2 个级别(默认)。
- 如果第一个参数是格式字符串(见下文):用于
util.format()
根据格式字符串打印剩余的参数(见下文);例如:o = { one: 1, two: 'deux', foo: function(){} }; console.log('o as JSON: %j', o) // -> 'o as JSON: {"one":1,"two":"deux"}'
- 笔记:
- 没有用于表示对象
util.inspect()
样式的占位符。 - 生成的 JSON
%j
不是漂亮的打印。
- 没有用于表示对象
- 如果第一个参数不是格式字符串:
- 仅接受1 个参数来检查,并且始终适用
util.inspect()
- 本质上,util.inspect()
默认情况下没有选项的包装器;例如: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+:可选的第二个参数指定选项
util.inspect()
– 见下文;例如:console.dir({ one: 1, two: 'deux'}, { colors: true }); // Node 0.11+: Prints object representation with syntax coloring.
- 仅接受1 个参数来检查,并且始终适用
- The REPL: implicitly prints any expression's return value with
util.inspect()
withsyntax 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.
- REPL:使用语法着色隐式打印任何表达式的返回值
util.inspect()
;
即,只需键入一个变量的名称并按 Enter 键将打印其值的检查版本;例如:o = { one: 1, two: 'deux', foo: function(){} } // The REPL echoes the object definition with syntax coloring.
util.inspect()
automatically pretty-prints objectand arrayrepresentations, but produces multilineoutput only when needed.
util.inspect()
自动漂亮地打印对象和数组表示,但仅在需要时生成多行输出。
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 charactersthanks, 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 singleline.
漂亮的打印行为可以由
compact
可选options
参数中的属性控制;无条件false
使用多行输出,而完全禁用漂亮打印;它也可以设置为一个数字(默认为)来控制条件多行行为 - 请参阅文档。true
3
默认情况下, 无论输出是发送到文件还是终端,输出都以大约 60 个字符换行,感谢Shrey。在实践中,由于换行只发生在属性边界处,你通常会得到较短的行,但它们也可以更长(例如,具有较长的属性值)。
在 v6.3.0+ 中,您可以使用该
breakLength
选项来覆盖 60 个字符的限制;如果你将它设置为Infinity
,一切都在输出单一线。
If you want more control over pretty-printing, consider using JSON.stringify()
with a 3rd argument, but note the following:
如果您想更好地控制漂亮打印,请考虑使用JSON.stringify()
第三个参数,但请注意以下几点:
- Failswith 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
- 使用具有循环引用的对象失败,例如
module
在全局上下文中。 - 方法(功能)将不包含在设计中。
- 您不能选择显示隐藏的(不可枚举的)属性。
- 示例调用:
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):
util.inspect()
选项对象(第二个参数):
An optional optionsobject may be passed that alters certain aspects of the formatted string; someof the properties supported are:
可以传递一个可选的选项对象来改变格式化字符串的某些方面;支持的一些属性是:
See the latest Node.js docsfor the current, full list.
有关当前的完整列表,请参阅最新的 Node.js 文档。
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
showHidden
- if
true
,则对象的不可枚举属性 [那些在您使用for keys in obj
或使用时指定不显示的属性Object.keys(obj)
] 也将显示。默认为false
.
- if
depth
- 告诉检查在格式化对象时要递归多少次。这对于检查大型复杂物体很有用。默认为 2。要使其无限递归,请传递
null
。
- 告诉检查在格式化对象时要递归多少次。这对于检查大型复杂物体很有用。默认为 2。要使其无限递归,请传递
colors
- 如果为 true,则输出将使用 ANSI 颜色代码进行样式设置。默认为
false
. 颜色是可定制的 [... – 见链接]。
- 如果为 true,则输出将使用 ANSI 颜色代码进行样式设置。默认为
customInspect
- if
false
,则inspect()
不会调用在被检查对象上定义的自定义函数。默认为true
.
- if
util.format()
format-string placeholders(1st argument)
util.format()
格式字符串占位符(第一个参数)
Someof the supported placeholders are:
一些受支持的占位符是:
See the latest Node.js docsfor the current, full list.
有关当前的完整列表,请参阅最新的 Node.js 文档。
%s
– String.%d
– Number (both integer and float).%j
– JSON.%%
– single percent sign (‘%'). This does not consume an argument.
%s
- 细绳。%d
– 数字(整数和浮点数)。%j
– JSON。%%
– 单个百分号 ('%')。这不消耗参数。
回答by niksmac
Another simple method is to convert it to json
另一种简单的方法是将其转换为json
console.log('connection : %j', myObject);
回答by hirra
Try this:
尝试这个:
console.dir(myObject,{depth:null})
回答by silverwind
Since Node.js 6.4.0, this can be elegantly solved with util.inspect.defaultOptions
:
从 Node.js 6.4.0 开始,这可以优雅地解决util.inspect.defaultOptions
:
require("util").inspect.defaultOptions.depth = null;
console.log(myObject);
回答by Luke W
perhaps console.dir
is all you need.
也许这console.dir
就是你所需要的。
http://nodejs.org/api/console.html#console_console_dir_obj
http://nodejs.org/api/console.html#console_console_dir_obj
Uses util.inspect on obj and prints resulting string to stdout.
在 obj 上使用 util.inspect 并将结果字符串打印到标准输出。
use util option if you need more control.
如果您需要更多控制,请使用 util 选项。
回答by Eesa
You can also do
你也可以这样做
console.log(JSON.stringify(myObject, null, 3));
回答by Ali
A good way to inspect objects is to use node --inspectoption with Chrome DevTools for Node.
检查对象的一个好方法是在Chrome DevTools for Node 中使用 node --inspect选项。
node.exe --inspect www.js
Open chrome://inspect/#devices
in chrome and click Open dedicated DevTools for Node
chrome://inspect/#devices
在 chrome 中打开并单击打开专用的 Node DevTools
Now every logged object is available in inspector like regular JS running in chrome.
现在每个记录的对象都可以在检查器中使用,就像在 chrome 中运行的常规 JS 一样。
There is no need to reopen inspector, it connects to node automatically as soon as node starts or restarts. Both --inspectand Chrome DevTools for Nodemay not be available in older versions of Node and Chrome.
无需重新打开检查器,它会在节点启动或重新启动时自动连接到节点。无论--inspect并为节点的Chrome DevTools可能无法在旧版本的节点和Chrome浏览器使用。
回答by Erce
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 });
// get a clear list of actual values
console.log(JSON.stringify(queryArgs, undefined, 2));