util.inspect(object[, showHidden[, depth[, colors]]])


  • object <any> 任何 JavaScript 原始类型或 Object
  • options <Object>
    • showHidden <boolean> 如果包括 true,那么 object 的不可枚举符号和属性也会包含在格式化结果中。同时还包括 WeakMapWeakSet 条目,以及用户定义的原型属性(不包括方法属性)。默认值: false
    • depth <number> 指定在格式化 object 时递归的次数。这对于检查大型对象非常有用。要递归到最大调用堆栈大小,请传入 Infinitynull默认值: 2
    • colors <boolean> 如果 true,输出将使用 ANSI 颜色代码进行样式化。颜色是可自定义的。参见 自定义 util.inspect 颜色默认值: false
    • customInspect <boolean> 如果未调用 false[util.inspect.custom](depth, opts, inspect) 函数。默认: true
    • showProxy <boolean> 如果 trueProxy 检查包括 targethandler 对象。默认值: false
    • maxArrayLength <integer> 指定在格式化时要包含的 ArrayTypedArrayMapSetWeakMapWeakSet 元素的最大数量。设置为 nullInfinity 可显示所有元素。设置为 0 或负数则不显示任何元素。默认值: 100
    • maxStringLength <integer> 指定格式化时要包含的最大字符数。设置为 nullInfinity 可显示所有元素。设置为 0 或负值则不显示任何字符。默认值: 10000
    • breakLength <integer> 输入值被拆分到多行的长度。设置为 Infinity 可以将输入格式化为单行(配合 compact 设置为 true 或任何大于等于 1 的数字)。默认值: 80
    • compact <boolean> | <integer> 将此设置为 false 会导致每个对象键显示在新的一行。当文本长度超过 breakLength 时,它会在新行处换行。如果设置为一个数字,最多 n 个内部元素会被合并在同一行,只要所有属性都能适应 breakLength。较短的数组元素也会被分组在一起。更多信息,请参见下面的示例。默认值: 3
    • sorted <boolean> | <Function> 如果设置为 true 或一个函数,对象的所有属性以及 SetMap 条目在生成的字符串中都会被排序。如果设置为 true,则使用 默认排序。如果设置为一个函数,它将作为 比较函数 使用。
    • getters <boolean> | <string> 如果设置为 true,将检查 getter。 如果设置为 'get',则只检查没有对应 setter 的 getter。 如果设置为 'set',则只检查有对应 setter 的 getter。 这可能会根据 getter 函数产生副作用。 默认值: false
    • numericSeparator <boolean> 如果设置为 true,所有大整数和数字中的每三位数字之间将使用下划线分隔。默认值: false
  • 返回:<string> object 的表示。

util.inspect() 方法返回一个 object 的字符串表示形式,旨在用于调试。util.inspect 的输出可能随时更改,不应在程序中依赖。可以传入额外的 options 来改变结果。util.inspect() 会使用构造函数的名称和/或 @@toStringTag 来为被检查的值生成一个可识别的标签。

🌐 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] }
// } 

下面的示例会检查 util 对象的所有属性:

🌐 The following example inspects all properties of the util object:

const util = require('node:util');

console.log(util.inspect(util, { showHidden: true, depth: null })); 

下面的例子强调了 compact 选项的效果:

🌐 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. 

showHidden 选项允许检查 WeakMapWeakSet 条目。如果条目数量超过 maxArrayLength,则无法保证显示哪些条目。这意味着两次检索相同的 WeakSet 条目可能会产生不同的输出。此外,没有剩余强引用的条目可能随时被垃圾回收。

🌐 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 } } 

sorted 选项确保对象的属性插入顺序不会影响 util.inspect() 的结果。

🌐 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 })
); 

numericSeparator 选项会在所有数字的每三位之间添加一个下划线。

🌐 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() 是一个用于调试的同步方法。其最大输出长度约为 128 MiB。超过此长度的输入将被截断。