自定义对象的查看函数


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

const util = require('util');

class Box {
  constructor(value) {
    this.value = value;
  }

  [util.inspect.custom](depth, options) {
    if (depth < 0) {
      return options.stylize('[Box]', 'special');
    }

    const newOptions = Object.assign({}, options, {
      depth: options.depth === null ? null : options.depth - 1
    });

    // 五个空格的填充,因为那是 "Box< " 的大小。
    const padding = ' '.repeat(5);
    const inner = util.inspect(this.value, newOptions)
                      .replace(/\n/g, `\n${padding}`);
    return `${options.stylize('Box', 'special')}< ${inner} >`;
  }
}

const box = new Box(true);

util.inspect(box);
// 返回: "Box< true >"

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

const util = require('util');

const obj = { foo: '这个不会出现在 inspect() 的输出中' };
obj[util.inspect.custom] = (depth) => {
  return { bar: 'baz' };
};

util.inspect(obj);
// 返回: "{ bar: 'baz' }"

Objects may also define their own [util.inspect.custom](depth, opts) (or the equivalent but deprecated inspect(depth, opts)) function, which util.inspect() will invoke and use the result of when inspecting the object:

const util = require('util');

class Box {
  constructor(value) {
    this.value = value;
  }

  [util.inspect.custom](depth, options) {
    if (depth < 0) {
      return options.stylize('[Box]', 'special');
    }

    const newOptions = Object.assign({}, options, {
      depth: options.depth === null ? null : options.depth - 1
    });

    // Five space padding because that's the size of "Box< ".
    const padding = ' '.repeat(5);
    const inner = util.inspect(this.value, newOptions)
                      .replace(/\n/g, `\n${padding}`);
    return `${options.stylize('Box', 'special')}< ${inner} >`;
  }
}

const box = new Box(true);

util.inspect(box);
// Returns: "Box< true >"

Custom [util.inspect.custom](depth, opts) functions typically return a string but may return a value of any type that will be formatted accordingly by util.inspect().

const util = require('util');

const obj = { foo: 'this will not show up in the inspect() output' };
obj[util.inspect.custom] = (depth) => {
  return { bar: 'baz' };
};

util.inspect(obj);
// Returns: "{ bar: 'baz' }"