Node.js 常用工具
util 模块是 Node.js 的一个内置模块,包含了实用工具函数,用于支持 JavaScript 编程中的调试、错误处理、格式化等功能。
util 提供常用函数的集合,用于弥补核心 JavaScript 的功能过于精简的不足。
util 模块中的功能涵盖了从对象检查、继承到格式化字符串等多个方面。
导入 util 模块
首先,你需要导入 util 模块:
<span style="background-color:#ecf4ee"><span style="color:#333333"><span style="color:#55859b">const</span><span style="color:#171c19"> util </span><span style="color:#171c19">=</span> <span style="color:#55859b">require</span><span style="color:#171c19">(</span><span style="color:#489963">'util'</span><span style="color:#171c19">);</span></span></span>
常用方法:
| 方法 | 描述 |
|---|---|
util.format(format, ...args) |
字符串格式化,支持 、、 占位符。%s%d%j |
util.inspect(object[, options]) |
将对象转换为字符串,用于调试。 |
util.promisify(function) |
将回调风格的函数转换为返回 Promise 的函数。 |
util.callbackify(fn) |
将返回 Promise 的函数转换为回调风格函数。 |
util.inherits(constructor, superConstructor) |
让一个构造函数继承另一个构造函数的原型方法。 |
util.deprecate(fn, message) |
标记函数为废弃,调用时会打印警告消息。 |
util.types |
包含多种类型检测方法的集合,例如 、。isAnyArrayBufferisBigInt64Array |
util.isDeepStrictEqual(val1, val2) |
判断两个值是否深度相等,类似于深度比较。 |
util.getSystemErrorName(err) |
根据错误码返回系统错误名称。 |
util.inspect.custom |
一个 Symbol,可以定义自定义的 行为,用于调试。inspect |
util.types 下的类型检测方法
util.types 是一个包含许多类型检测方法的集合,扩展了 JavaScript 的 typeof 和 instanceof。
| 方法 | 描述 |
|---|---|
util.types.isAnyArrayBuffer(value) |
检查值是否为 或 。ArrayBufferSharedArrayBuffer |
util.types.isArrayBuffer(value) |
检查值是否为 。ArrayBuffer |
util.types.isAsyncFunction(value) |
检查值是否为异步函数。 |
util.types.isBigInt64Array(value) |
检查值是否为 。BigInt64Array |
util.types.isBigUint64Array(value) |
检查值是否为 。BigUint64Array |
util.types.isBooleanObject(value) |
检查值是否为布尔对象。 |
util.types.isDataView(value) |
检查值是否为 。DataView |
util.types.isDate(value) |
检查值是否为 。Date |
util.types.isGeneratorFunction(value) |
检查值是否为生成器函数。 |
util.types.isMap(value) |
检查值是否为 。Map |
util.types.isSet(value) |
检查值是否为 。Set |
util.types.isRegExp(value) |
检查值是否为正则表达式。 |
util.types.isSymbolObject(value) |
检查值是否为符号对象。 |
应用实例
util.format() - 字符串格式化
util.format() 用于生成格式化字符串,支持占位符如 %s、%d 和 %j,分别代表字符串、数字和 JSON。
实例
const util = require(

最低0.47元/天 解锁文章
2万+

被折叠的 条评论
为什么被折叠?



