util.inspect(object[, showHidden[, depth[, colors]]])
object
<any> 任何 JavaScript 原始类型或Object
。options
<Object>showHidden
<boolean> 如果为true
,则object
的不可枚举符号和属性包含在格式化的结果中。WeakMap
和WeakSet
条目以及用户定义的原型属性(不包括方法属性)也包括在内。 默认值:false
。depth
<number> 指定格式化object
时递归的次数。 这对于检查大型对象很有用。 要递归到最大调用堆栈大小,则传入Infinity
或null
。 默认值:2
。colors
<boolean> 如果为true
,则输出的样式为 ANSI 颜色代码。 颜色是可自定义的。 参阅自定义util.inspect
颜色。 默认值:false
。customInspect
<boolean> 如果为false
,则[util.inspect.custom](depth, opts, inspect)
函数不被调用。 默认值:true
。showProxy
<boolean> 如果为true
,则Proxy
检查包括target
和handler
对象。 默认值:false
。maxArrayLength
<integer> 指定格式化时要包含的Array
、TypedArray
、WeakMap
和WeakSet
元素的最大数量。 设置为null
或Infinity
则显示所有元素。 设置为0
或负数则不显示任何元素。 默认值:100
。maxStringLength
<integer> 指定格式化时要包含的最大字符数。 设置为null
或Infinity
则显示所有元素。 设置为0
或负数则不显示字符。 默认值:10000
。breakLength
<integer> 输入值在多行中拆分的长度。 设置为Infinity
则将输入格式化为单行(与设置为true
或任何数字 >=1
的compact
组合)。 默认值:80
。compact
<boolean> | <integer> 将此设置为false
会导致每个对象的键显示在新行上。 它将在比breakLength
长的文本中换行。 如果设置为数字,则只要所有属性都适合breakLength
,则最多n
个内部元素将合并在一行中。 短数组元素也组合在一起。 有关更多信息,请参阅下面的示例。 默认值:3
。sorted
<boolean> | <Function> 如果设置为true
或函数,则对象的所有属性以及Set
和Map
条目都将在结果字符串中排序。 如果设置为true
,则使用默认的排序。 如果设置为函数,则用作比较函数。getters
<boolean> | <string> 如果设置为true
,则检查获取器。 如果设置为'get'
,则只检查没有相应设置器的获取器。 如果设置为'set'
,则只检查具有相应设置器的获取器。 这可能会导致副作用,具体取决于获取器函数。 默认值:false
。numericSeparator
<boolean> 如果设置为true
,则使用下划线分隔所有 bigint 和数字中的每三个数字。 默认值:false
。
- 返回: <string>
object
的表示。
util.inspect()
方法返回用于调试的 object
的字符串表示。
util.inspect
的输出可能随时更改,不应以编程方式依赖。
可以传入额外的 options
来改变结果。
util.inspect()
将使用构造函数的名称和/或 @@toStringTag
为检查的值制作可识别的标签。
class Foo {
get [Symbol.toStringTag]() {
return 'bar';
}
}
class Bar {}
const baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } });
util.inspect(new Foo()); // 'Foo [bar] {}'
util.inspect(new Bar()); // 'Bar {}'
util.inspect(baz); // '[foo] {}'
循环引用通过使用引用索引指向其锚点:
const { inspect } = require('node:util');
const obj = {};
obj.a = [obj];
obj.b = {};
obj.b.inner = obj.b;
obj.b.obj = obj;
console.log(inspect(obj));
// <ref *1> {
// a: [ [Circular *1] ],
// b: <ref *2> { inner: [Circular *2], obj: [Circular *1] }
// }
以下示例检查 util
对象的所有属性:
const util = require('node:util');
console.log(util.inspect(util, { showHidden: true, depth: null }));
以下示例高亮了 compact
选项的效果:
const util = require('node:util');
const o = {
a: [1, 2, [[
'Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit, sed do ' +
'eiusmod \ntempor incididunt ut labore et dolore magna aliqua.',
'test',
'foo']], 4],
b: new Map([['za', 1], ['zb', 'test']])
};
console.log(util.inspect(o, { compact: true, depth: 5, breakLength: 80 }));
// { a:
// [ 1,
// 2,
// [ [ 'Lorem ipsum dolor sit amet,\nconsectetur [...]', // A long line
// 'test',
// 'foo' ] ],
// 4 ],
// b: Map(2) { 'za' => 1, 'zb' => 'test' } }
// 将 `compact` 设置为 false 或整数会创建更友好的输出。
console.log(util.inspect(o, { compact: false, depth: 5, breakLength: 80 }));
// {
// a: [
// 1,
// 2,
// [
// [
// 'Lorem ipsum dolor sit amet,\n' +
// 'consectetur adipiscing elit, sed do eiusmod \n' +
// 'tempor incididunt ut labore et dolore magna aliqua.',
// 'test',
// 'foo'
// ]
// ],
// 4
// ],
// b: Map(2) {
// 'za' => 1,
// 'zb' => 'test'
// }
// }
// 将 `breakLength` 设置为例如 150,
// 则将在一行中打印 "Lorem ipsum" 文本。
showHidden
选项允许检查 WeakMap
和 WeakSet
条目。
如果条目多于 maxArrayLength
,则无法保证显示哪些条目。
这意味着两次检索相同的 WeakSet
条目可能会导致不同的输出。
此外,没有剩余强引用的条目可能随时被垃圾回收。
const { inspect } = require('node:util');
const obj = { a: 1 };
const obj2 = { b: 2 };
const weakSet = new WeakSet([obj, obj2]);
console.log(inspect(weakSet, { showHidden: true }));
// WeakSet { { a: 1 }, { b: 2 } }
sorted
选项确保对象的属性插入顺序不会影响 util.inspect()
的结果。
const { inspect } = require('node:util');
const assert = require('node:assert');
const o1 = {
b: [2, 3, 1],
a: '`a` comes before `b`',
c: new Set([2, 3, 1])
};
console.log(inspect(o1, { sorted: true }));
// { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set(3) { 1, 2, 3 } }
console.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) }));
// { c: Set(3) { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' }
const o2 = {
c: new Set([2, 1, 3]),
a: '`a` comes before `b`',
b: [2, 3, 1]
};
assert.strict.equal(
inspect(o1, { sorted: true }),
inspect(o2, { sorted: true })
);
numericSeparator
选项为所有数字每三位添加一个下划线。
const { inspect } = require('node:util');
const thousand = 1_000;
const million = 1_000_000;
const bigNumber = 123_456_789n;
const bigDecimal = 1_234.123_45;
console.log(thousand, million, bigNumber, bigDecimal);
// 1_000 1_000_000 123_456_789n 1_234.123_45
util.inspect()
是用于调试的同步方法。
其最大输出长度约为 128 MiB。
造成更长输出的输入将被截断。
object
<any> Any JavaScript primitive orObject
.options
<Object>showHidden
<boolean> Iftrue
,object
's non-enumerable symbols and properties are included in the formatted result.WeakMap
andWeakSet
entries are also included as well as user defined prototype properties (excluding method properties). Default:false
.depth
<number> Specifies the number of times to recurse while formattingobject
. This is useful for inspecting large objects. To recurse up to the maximum call stack size passInfinity
ornull
. Default:2
.colors
<boolean> Iftrue
, the output is styled with ANSI color codes. Colors are customizable. See Customizingutil.inspect
colors. Default:false
.customInspect
<boolean> Iffalse
,[util.inspect.custom](depth, opts, inspect)
functions are not invoked. Default:true
.showProxy
<boolean> Iftrue
,Proxy
inspection includes thetarget
andhandler
objects. Default:false
.maxArrayLength
<integer> Specifies the maximum number ofArray
,TypedArray
,WeakMap
, andWeakSet
elements to include when formatting. Set tonull
orInfinity
to show all elements. Set to0
or negative to show no elements. Default:100
.maxStringLength
<integer> Specifies the maximum number of characters to include when formatting. Set tonull
orInfinity
to show all elements. Set to0
or negative to show no characters. Default:10000
.breakLength
<integer> The length at which input values are split across multiple lines. Set toInfinity
to format the input as a single line (in combination withcompact
set totrue
or any number >=1
). Default:80
.compact
<boolean> | <integer> Setting this tofalse
causes each object key to be displayed on a new line. It will break on new lines in text that is longer thanbreakLength
. If set to a number, the mostn
inner elements are united on a single line as long as all properties fit intobreakLength
. Short array elements are also grouped together. For more information, see the example below. Default:3
.sorted
<boolean> | <Function> If set totrue
or a function, all properties of an object, andSet
andMap
entries are sorted in the resulting string. If set totrue
the default sort is used. If set to a function, it is used as a compare function.getters
<boolean> | <string> If set totrue
, getters are inspected. If set to'get'
, only getters without a corresponding setter are inspected. If set to'set'
, only getters with a corresponding setter are inspected. This might cause side effects depending on the getter function. Default:false
.numericSeparator
<boolean> If set totrue
, an underscore is used to separate every three digits in all bigints and numbers. Default:false
.
- Returns: <string> The representation of
object
.
The util.inspect()
method returns a string representation of object
that is
intended for debugging. The output of util.inspect
may change at any time
and should not be depended upon programmatically. Additional options
may be
passed that alter the result.
util.inspect()
will use the constructor's name and/or @@toStringTag
to make
an identifiable tag for an inspected value.
class Foo {
get [Symbol.toStringTag]() {
return 'bar';
}
}
class Bar {}
const baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } });
util.inspect(new Foo()); // 'Foo [bar] {}'
util.inspect(new Bar()); // 'Bar {}'
util.inspect(baz); // '[foo] {}'
Circular references point to their anchor by using a reference index:
const { inspect } = require('node:util');
const obj = {};
obj.a = [obj];
obj.b = {};
obj.b.inner = obj.b;
obj.b.obj = obj;
console.log(inspect(obj));
// <ref *1> {
// a: [ [Circular *1] ],
// b: <ref *2> { inner: [Circular *2], obj: [Circular *1] }
// }
The following example inspects all properties of the util
object:
const util = require('node:util');
console.log(util.inspect(util, { showHidden: true, depth: null }));
The following example highlights the effect of the compact
option:
const util = require('node:util');
const o = {
a: [1, 2, [[
'Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit, sed do ' +
'eiusmod \ntempor incididunt ut labore et dolore magna aliqua.',
'test',
'foo']], 4],
b: new Map([['za', 1], ['zb', 'test']])
};
console.log(util.inspect(o, { compact: true, depth: 5, breakLength: 80 }));
// { a:
// [ 1,
// 2,
// [ [ 'Lorem ipsum dolor sit amet,\nconsectetur [...]', // A long line
// 'test',
// 'foo' ] ],
// 4 ],
// b: Map(2) { 'za' => 1, 'zb' => 'test' } }
// Setting `compact` to false or an integer creates more reader friendly output.
console.log(util.inspect(o, { compact: false, depth: 5, breakLength: 80 }));
// {
// a: [
// 1,
// 2,
// [
// [
// 'Lorem ipsum dolor sit amet,\n' +
// 'consectetur adipiscing elit, sed do eiusmod \n' +
// 'tempor incididunt ut labore et dolore magna aliqua.',
// 'test',
// 'foo'
// ]
// ],
// 4
// ],
// b: Map(2) {
// 'za' => 1,
// 'zb' => 'test'
// }
// }
// Setting `breakLength` to e.g. 150 will print the "Lorem ipsum" text in a
// single line.
The showHidden
option allows WeakMap
and WeakSet
entries to be
inspected. If there are more entries than maxArrayLength
, there is no
guarantee which entries are displayed. That means retrieving the same
WeakSet
entries twice may result in different output. Furthermore, entries
with no remaining strong references may be garbage collected at any time.
const { inspect } = require('node:util');
const obj = { a: 1 };
const obj2 = { b: 2 };
const weakSet = new WeakSet([obj, obj2]);
console.log(inspect(weakSet, { showHidden: true }));
// WeakSet { { a: 1 }, { b: 2 } }
The sorted
option ensures that an object's property insertion order does not
impact the result of util.inspect()
.
const { inspect } = require('node:util');
const assert = require('node:assert');
const o1 = {
b: [2, 3, 1],
a: '`a` comes before `b`',
c: new Set([2, 3, 1])
};
console.log(inspect(o1, { sorted: true }));
// { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set(3) { 1, 2, 3 } }
console.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) }));
// { c: Set(3) { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' }
const o2 = {
c: new Set([2, 1, 3]),
a: '`a` comes before `b`',
b: [2, 3, 1]
};
assert.strict.equal(
inspect(o1, { sorted: true }),
inspect(o2, { sorted: true })
);
The numericSeparator
option adds an underscore every three digits to all
numbers.
const { inspect } = require('node:util');
const thousand = 1_000;
const million = 1_000_000;
const bigNumber = 123_456_789n;
const bigDecimal = 1_234.123_45;
console.log(thousand, million, bigNumber, bigDecimal);
// 1_000 1_000_000 123_456_789n 1_234.123_45
util.inspect()
is a synchronous method intended for debugging. Its maximum
output length is approximately 128 MiB. Inputs that result in longer output will
be truncated.