Appearance
工具模块
util 模块提供常用的工具函数。
js
const util = require('util');util.format(format[, ...args])
格式化字符串,类似 printf。
支持的占位符:
%s- 字符串%d- 数字(整数或浮点数)%i- 整数%f- 浮点数%j- JSON(循环引用显示'[Circular]')%o- 对象(显示完整信息)%O- 对象(简化显示)%%- 单个百分号%
js
util.format('%s:%s', 'foo'); // 'foo:%s'
util.format('%s:%s', 'foo', 'bar'); // 'foo:bar'
util.format(1, 2, 3); // '1 2 3'util.inspect(object[, options])
返回对象的字符串表示,主要用于调试。
参数选项:
showHidden{boolean} - 是否显示不可枚举属性,默认falsedepth{number} - 递归深度,默认2,null表示无限colors{boolean} - 是否使用颜色,默认falsecustomInspect{boolean} - 是否调用自定义 inspect 方法,默认truemaxArrayLength{number} - 数组最大显示长度,默认100
js
const obj = { name: 'test', nested: { a: 1, b: [1, 2, 3] } };
console.log(util.inspect(obj));
// '{ name: 'test', nested: { a: 1, b: [ 1, 2, 3 ] } }'
console.log(util.inspect(obj, { depth: null, colors: true }));
// 完整显示,带颜色util.promisify(original)
将回调风格的函数转换为返回 Promise 的版本。
js
const fs = require('fs');
const stat = util.promisify(fs.stat);
// 使用 Promise
stat('.').then((stats) => {
console.log(stats);
}).catch((err) => {
console.error(err);
});
// 使用 async/await
async function callStat() {
const stats = await stat('.');
console.log(`目录所有者: ${stats.uid}`);
}util.callbackify(original)
将 async 函数转换为回调风格。
js
async function fn() {
return await Promise.resolve('hello world');
}
const callbackFunction = util.callbackify(fn);
callbackFunction((err, ret) => {
if (err) throw err;
console.log(ret); // 'hello world'
});util.debuglog(section)
创建条件调试日志函数,根据 NODE_DEBUG 环境变量决定是否输出。
js
const debuglog = util.debuglog('myapp');
debuglog('调试信息 [%d]', 123);设置环境变量 NODE_DEBUG=myapp 后才会输出:
MYAPP 1234: 调试信息 [123]util.deprecate(function, string)
标记函数为已弃用,调用时会发出警告。
js
exports.oldFunction = util.deprecate(function() {
// 旧逻辑
}, 'oldFunction: 请使用 newFunction 替代');