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) 函数不被调用。 默认值: true
    • showProxy <boolean> 如果为 true,则 Proxy 检查包括 targethandler 对象。 默认值: false
    • maxArrayLength <integer> 指定格式化时要包含的 ArrayTypedArrayWeakMapWeakSet 元素的最大数量。 设置为 nullInfinity 则显示所有元素。 设置为 0 或负数则不显示任何元素。 默认值: 100
    • maxStringLength <integer> 指定格式化时要包含的最大字符数。 设置为 nullInfinity 则显示所有元素。 设置为 0 或负数则不显示字符。 默认值: Infinity
    • breakLength <integer> 输入值在多行中拆分的长度。 设置为 Infinity 则将输入格式化为单行(与设置为 true 或任何数字 >= 1compact 组合)。 默认值: 80
    • compact <boolean> | <integer> 将此设置为 false 会导致每个对象的键显示在新行上。 它还会向比 breakLength 长的文本添加新行。 如果设置为数字,则只要所有属性都适合 breakLength,则最多 n 个内部元素将合并在一行中。 短数组元素也组合在一起。 无论 breakLength 大小如何,文本都不会减少到 16 个字符以下。 有关更多信息,请参阅下面的示例。 默认值: 3
    • sorted <boolean> | <Function> 如果设置为 true 或函数,则对象的所有属性以及 SetMap 条目都将在结果字符串中排序。 如果设置为 true,则使用默认的排序。 如果设置为函数,则用作比较函数
    • getters <boolean> | <string> 如果设置为 true,则检查获取器。 如果设置为 'get',则只检查没有相应设置器的获取器。 如果设置为 'set',则只检查具有相应设置器的获取器。 这可能会导致副作用,具体取决于获取器函数。 默认值: 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('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('util');

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

以下示例高亮了 compact 选项的效果:

const util = require('util');

const o = {
  a: [1, 2, [[
    'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do ' +
      'eiusmod tempor 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, consectetur [...]', // 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, consectetur ' +
//           'adipiscing elit, sed do eiusmod tempor ' +
//           'incididunt ut labore et dolore magna ' +
//           'aliqua.,
//         'test',
//         'foo'
//       ]
//     ],
//     4
//   ],
//   b: Map(2) {
//     'za' => 1,
//     'zb' => 'test'
//   }
// }

// 将 `breakLength` 设置为例如 150,
// 则将在一行中打印 "Lorem ipsum" 文本。
// 减少 `breakLength` 会将 "Lorem ipsum" 文本分成
// 更小的块。

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

const { inspect } = require('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('util');
const assert = require('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 })
);

util.inspect() 是用于调试的同步方法。 其最大输出长度约为 128 MB。 造成更长输出的输入将被截断。

  • object <any> Any JavaScript primitive or Object.
  • options <Object>
    • showHidden <boolean> If true, object's non-enumerable symbols and properties are included in the formatted result. WeakMap and WeakSet 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 formatting object. This is useful for inspecting large objects. To recurse up to the maximum call stack size pass Infinity or null. Default: 2.
    • colors <boolean> If true, the output is styled with ANSI color codes. Colors are customizable. See Customizing util.inspect colors. Default: false.
    • customInspect <boolean> If false, [util.inspect.custom](depth, opts) functions are not invoked. Default: true.
    • showProxy <boolean> If true, Proxy inspection includes the target and handler objects. Default: false.
    • maxArrayLength <integer> Specifies the maximum number of Array, TypedArray, WeakMap and WeakSet elements to include when formatting. Set to null or Infinity to show all elements. Set to 0 or negative to show no elements. Default: 100.
    • maxStringLength <integer> Specifies the maximum number of characters to include when formatting. Set to null or Infinity to show all elements. Set to 0 or negative to show no characters. Default: Infinity.
    • breakLength <integer> The length at which input values are split across multiple lines. Set to Infinity to format the input as a single line (in combination with compact set to true or any number >= 1). Default: 80.
    • compact <boolean> | <integer> Setting this to false causes each object key to be displayed on a new line. It will also add new lines to text that is longer than breakLength. If set to a number, the most n inner elements are united on a single line as long as all properties fit into breakLength. Short array elements are also grouped together. No text will be reduced below 16 characters, no matter the breakLength size. For more information, see the example below. Default: 3.
    • sorted <boolean> | <Function> If set to true or a function, all properties of an object, and Set and Map entries are sorted in the resulting string. If set to true the default sort is used. If set to a function, it is used as a compare function.
    • getters <boolean> | <string> If set to true, 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.
  • 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('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('util');

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

The following example highlights the effect of the compact option:

const util = require('util');

const o = {
  a: [1, 2, [[
    'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do ' +
      'eiusmod tempor 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, consectetur [...]', // A long line
//           'test',
//           'foo' ] ],
//     4 ],
//   b: Map(2) { 'za' => 1, 'zb' => 'test' } }

// Setting `compact` to false changes the output to be more reader friendly.
console.log(util.inspect(o, { compact: false, depth: 5, breakLength: 80 }));

// {
//   a: [
//     1,
//     2,
//     [
//       [
//         'Lorem ipsum dolor sit amet, consectetur ' +
//           'adipiscing elit, sed do eiusmod 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.
// Reducing the `breakLength` will split the "Lorem ipsum" text in smaller
// chunks.

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('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('util');
const assert = require('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 })
);

util.inspect() is a synchronous method intended for debugging. Its maximum output length is approximately 128 MB. Inputs that result in longer output will be truncated.