对象可以定义自己的 [[util.inspect.custom](depth, opts)][util.inspect.custom] 函数,util.inspect() 会调用并使用查看对象时的结果:

    1. const util = require('util');
    2. class Box {
    3. constructor(value) {
    4. this.value = value;
    5. }
    6. [util.inspect.custom](depth, options) {
    7. if (depth < 0) {
    8. return options.stylize('[Box]', 'special');
    9. }
    10. const newOptions = Object.assign({}, options, {
    11. depth: options.depth === null ? null : options.depth - 1
    12. });
    13. // 五个空格的填充,因为那是 "Box< " 的大小。
    14. const padding = ' '.repeat(5);
    15. const inner = util.inspect(this.value, newOptions)
    16. .replace(/\n/g, `\n${padding}`);
    17. return `${options.stylize('Box', 'special')}< ${inner} >`;
    18. }
    19. }
    20. const box = new Box(true);
    21. util.inspect(box);
    22. // 返回: "Box< true >"

    自定义的 [util.inspect.custom](depth, opts) 函数通常返回一个字符串,但也可以返回一个任何类型的值,它会相应地被 util.inspect() 格式化。

    1. const util = require('util');
    2. const obj = { foo: '这个不会出现在 inspect() 的输出中' };
    3. obj[util.inspect.custom] = (depth) => {
    4. return { bar: 'baz' };
    5. };
    6. util.inspect(obj);
    7. // 返回: "{ bar: 'baz' }"