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


  • object <any> 任何 JavaScript 原始类型或 Object
  • options <Object>
    • showHidden <boolean> 如果为 true,则 object 的非枚举符号和属性会包含在格式化结果中。WeakMap 和 WeakSet 条目也会被包含,以及用户定义的原型属性(不包括方法属性)。默认值: 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> 指定在格式化时包含的 Array<TypedArray><Map>、WeakMap 和 WeakSet 元素的最大数量。设置为 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() 会使用构造函数的名称和/或 Symbol.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 Symbol.toStringTag property 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:】

import { inspect } from '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] }
// }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:】

import util from 'node:util';

console.log(util.inspect(util, { showHidden: true, depth: null }));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:】

import { inspect } from '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(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(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.const { inspect } = 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(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(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 选项允许检查 WeakMap 和 WeakSet 条目。如果条目数量超过 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.】

import { inspect } from '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 } }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().】

import { inspect } from 'node:util';
import assert from '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 }),
);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.】

import { inspect } from 'node:util';

const thousand = 1000;
const million = 1000000;
const bigNumber = 123456789n;
const bigDecimal = 1234.12345;

console.log(inspect(thousand, { numericSeparator: true }));
// 1_000
console.log(inspect(million, { numericSeparator: true }));
// 1_000_000
console.log(inspect(bigNumber, { numericSeparator: true }));
// 123_456_789n
console.log(inspect(bigDecimal, { numericSeparator: true }));
// 1_234.123_45const { inspect } = require('node:util');

const thousand = 1000;
const million = 1000000;
const bigNumber = 123456789n;
const bigDecimal = 1234.12345;

console.log(inspect(thousand, { numericSeparator: true }));
// 1_000
console.log(inspect(million, { numericSeparator: true }));
// 1_000_000
console.log(inspect(bigNumber, { numericSeparator: true }));
// 123_456_789n
console.log(inspect(bigDecimal, { numericSeparator: true }));
// 1_234.123_45

util.inspect() 是一个用于调试的同步方法。其最大输出长度约为 128 MiB。超过此长度的输入将被截断。