23-实用工具模块-util

106 阅读2分钟

实用工具模块-util

debuglog(section)

// 这是一个很有用的调试方法,可以通过 util.debuglog(name) 来创建一个调试fn,这个fn的特点是,只有在运行程序的时候,声明环境变量NODE_DEBUG=name 才会打印出调试信息
// 可以看下面的例子,直接运行 node debuglog.js 没有任何输出,需要 NODE_DEBUG=foo 才能打印出信息

const logger = util.debuglog("foo");
logger("hello");
// $ NODE_DEBUG=foo node index.js
// FOO 38948: hello

// 此外还可以执行多个 name 通过逗号分隔
const one = util.debuglog("one");
const two = util.debuglog("two");
const three = util.debuglog("three");
one("hello");
two("你好");
three("萨瓦迪卡");
// $ NODE_DEBUG=one,two,three node index.js
// ONE 27996: hello
// TWO 27996: 你好
// THREE 27996: 萨瓦迪卡

将方法标识为作为 util.deprecate(fn,str)

// 将fn包裹一层,并返回一个新的函数fn2,调用fn2时同时调用fn,同样完成fn原有的功能,但是同时会打印出错误日志,提示方法已经作废,具体的提示信息有第二个参数str来决定

const foo = function () {
  console.log("foo");
};
const foo2 = util.deprecate(foo, "foo已经作废了");
foo2();
// foo
// (node:41476) DeprecationWarning: foo已经作废了
// (Use `node --trace-deprecation ...` to show where the warning was created)

格式化打印 util.format(format,...args)

// 格式化打印大家应经很熟悉了,基本每个语言都有自己的实现

console.log(util.format("hello %s", "world")); // hello world
console.log(util.format("hello %s", "world1")); // hello world1

console.log(util.format("1+1 = %d", 2)); // 1+1 = 2
console.log(util.format("1+1 = %d", 3)); // 1+1 = 3

console.log(util.format("info %j", { nick: "lgq" })); // info {"nick":"lgq"}
console.log(util.format("info %j", { nick: "lgq1" })); // info {"nick":"lgq1"}

console.log(util.format("%s is %d age old", "lgq", 2)); // lgq is 2 age old
console.log(util.format("%s is %d age old", "LGQ", 20)); // LGQ is 20 age old

console.log(util.format("%s is a man", "LGQ", "321")); // LGQ is a man 321
console.log(util.format("%s is a man", "LGQ", "123")); // LGQ is a man 123

调试方法 util.inspect(obj,options)

// 非常实用的一个方法,参数说明如下
// obj: js原始值,或者对象
// options: 配置参数,包含下面选项
// showHidden 如果是true的话,obj的非枚举属性也会被展示出来,默认是false
// depth 如果是obj对象,那么depth限制对象递归展示的层级,这对可读性有一定的好处,默认是2,如果设置为null,则不做限制
// colors 自定义配色方法
// showProxy
// maxArrayLength 如果是obj的数组,那么限制最大可展示的数组个数,默认是100,如果设置为null,则不做显示,如果设置为0或者负数,则一个都不展示

let obj = {};
Object.defineProperty(obj, "nick", {
  enumerable: false,
  value: "lgq",
});
console.log(util.inspect(obj)); // {}
console.log(util.inspect(obj, { showHidden: true })); // { [nick]: 'lgq' }