一个对象的序列化输出函数通常用于Log输出或调试工具查看用。如需要自定义对象的序列化函数可以使用util.inspect.custom定义函数输出对象的序列化字符串表达。有如下两种方法定义:
- 使用ES6新定义的数据类型:Symbol 如下
const inspect = Symbol.for('nodejs.util.inspect.custom');
class Password {
constructor(value) {
this.value = value;
}
toString() {
return 'xxxxxxxx';
}
[inspect]() {
return `Password <${this.toString()}>`;
}
}
const password = new Password('r0sebud');
console.log(password);
// Prints Password <xxxxxxxx>
- 直接在对象里定义
const util = require('util');
const obj = { foo: '这个不会出现在 inspect() 的输出中' };
obj[util.inspect.custom] = (depth) => {
return { bar: 'baz' };
};
util.inspect(obj);
// 返回: "{ bar: 'baz' }"
该函数可携带两个参数
[util.inspect.custom](depth, opts)
一般默认调用对象的序列化函数不使用参数,如果想借助这两个参数输出复杂形势的对象序列化内容,可以使用如下函数传递相应参数util.inspect(object[, options])
options参数一部分常用的如下
- showHidden - 是否枚举显示对象的隐藏属性。默认为 false
- depth - 设置对象枚举显示的深度。默认为2,设置为null时将无穷递归显示
- colors - 如果设为true,将会以ANSI颜色代码风格进行输出。默认为 false
- customInspect - 如果设为 false,那么定义在被检查对象上的inspect(depth, opts) 方法将不会被调用。 默认为true。
使用时可形如:
var util = require('util');
//输出util中的对象信息
console.log(util.inspect(util, { showHidden: true, depth: null }));