Node.js入门教程(二十四):常用工具(util 模块)

发布时间:2026/8/15 23:08:20
Node.js入门教程(二十四):常用工具(util 模块) 一、util 模块概述util模块是 Node.js 的一个内置模块包含了实用工具函数用于支持 JavaScript 编程中的调试、错误处理、格式化等功能。util提供常用函数的集合用于弥补核心 JavaScript 的功能过于精简的不足。util模块中的功能涵盖了从对象检查、继承到格式化字符串等多个方面。二、导入 util 模块const util require(util);三、常用方法概览方法描述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包含多种类型检测方法的集合util.isDeepStrictEqual(val1, val2)判断两个值是否深度相等util.getSystemErrorName(err)根据错误码返回系统错误名称四、常用方法详解util.format() - 字符串格式化util.format()用于生成格式化字符串支持占位符如%s、%d和%j分别代表字符串、数字和 JSON。const util require(util); const name Alice; const age 25; console.log(util.format(Name: %s, Age: %d, name, age)); // 输出: Name: Alice, Age: 25 console.log(util.format(JSON: %j, { key: value })); // 输出: JSON: {key:value}util.promisify() - 转换回调函数为 Promiseutil.promisify()将传统回调风格的函数转换为返回 Promise 的函数从而可以与async/await一起使用。const util require(util); const fs require(fs); // 将回调风格的 fs.readFile 转换为返回 Promise 的函数 const readFileAsync util.promisify(fs.readFile); (async () { try { const data await readFileAsync(example.txt, utf8); console.log(data); } catch (err) { console.error(err); } })();util.callbackify() - 将 Promise 转换为回调util.callbackify()将返回 Promise 的函数转换为回调风格的函数便于在需要回调的代码环境中使用。util.callbackify(original)将async异步函数或者一个返回值为 Promise 的函数转换成遵循异常优先的回调风格的函数即将(err, value) ...回调作为最后一个参数。在回调函数中第一个参数为拒绝的原因如果 Promise 解决则为null第二个参数则是解决的值。const util require(util); async function fn() { return hello world; } const callbackFunction util.callbackify(fn); callbackFunction((err, ret) { if (err) throw err; console.log(ret); });输出结果hello world注意回调函数是异步执行的并且有异常堆栈错误追踪。如果回调函数抛出一个异常进程会触发一个uncaughtException异常如果没有被捕获进程将会退出。特殊处理如果回调函数的首个参数为 Promise 拒绝的原因且带有返回值且值可以转换成布尔值false这个值会被封装在Error对象里可以通过属性reason获取。function fn() { return Promise.reject(null); } const callbackFunction util.callbackify(fn); callbackFunction((err, ret) { // 当 Promise 被以 null 拒绝时它被包装为 Error 并且原始值存储在 reason 中 err err.hasOwnProperty(reason) err.reason null; // true });util.deprecate() - 标记函数为废弃util.deprecate()用于标记不推荐使用的函数调用时会显示警告信息。const util require(util); const oldFunction util.deprecate(() { console.log(This function is deprecated); }, oldFunction is deprecated. Use newFunction instead.); oldFunction(); // 调用时会显示警告util.inherits() - 实现继承util.inherits(constructor, superConstructor)是一个实现对象间原型继承的函数。JavaScript 的面向对象特性是基于原型的与常见的基于类的不同。JavaScript 没有提供对象继承的语言级别特性而是通过原型复制来实现的。var util require(util); function Base() { this.name base; this.base 1991; this.sayHello function() { console.log(Hello this.name); }; } Base.prototype.showName function() { console.log(this.name); }; function Sub() { this.name sub; } util.inherits(Sub, Base); var objBase new Base(); objBase.showName(); // base objBase.sayHello(); // Hello base console.log(objBase); // { name: base, base: 1991, sayHello: [Function] } var objSub new Sub(); objSub.showName(); // sub console.log(objSub); // { name: sub }运行结果base Hello base { name: base, base: 1991, sayHello: [Function] } sub { name: sub }注意Sub仅仅继承了Base在原型中定义的函数如showName而构造函数内部创建的base属性和sayHello函数都没有被Sub继承。如果去掉objSub.sayHello();这行的注释将会看到错误TypeError: Object #Sub has no method sayHello提示在 ES6 出现之前util.inherits是 Node.js 中实现继承的主要方法。但是ES6 之后推荐使用class和extends语法这样继承的代码更具可读性。util.inspect() - 打印对象结构util.inspect(object[, options])将对象转换为字符串表示形式便于调试。可以指定options参数来控制输出格式。const util require(util); const obj { a: 1, b: 2, c: { d: 3 } }; console.log(util.inspect(obj, { showHidden: false, depth: null, colors: true }));五、util.types 类型检测方法util.types是一个包含许多类型检测方法的集合扩展了 JavaScript 的typeof和instanceof。const util require(util); console.log(util.types.isDate(new Date())); // true console.log(util.types.isMap(new Map())); // true console.log(util.types.isSet(new Set())); // true console.log(util.types.isRegExp(/test/)); // true console.log(util.types.isAsyncFunction(async () {})); // true常用类型检测方法方法描述util.types.isAnyArrayBuffer(value)检查是否为 ArrayBuffer 或 SharedArrayBufferutil.types.isArrayBuffer(value)检查是否为 ArrayBufferutil.types.isAsyncFunction(value)检查是否为异步函数util.types.isBigInt64Array(value)检查是否为 BigInt64Arrayutil.types.isBigUint64Array(value)检查是否为 BigUint64Arrayutil.types.isBooleanObject(value)检查是否为布尔对象util.types.isDataView(value)检查是否为 DataViewutil.types.isDate(value)检查是否为 Dateutil.types.isGeneratorFunction(value)检查是否为生成器函数util.types.isMap(value)检查是否为 Maputil.types.isSet(value)检查是否为 Setutil.types.isRegExp(value)检查是否为正则表达式util.types.isSymbolObject(value)检查是否为符号对象六、旧版工具方法已废弃以下方法在较新版本的 Node.js 中已废弃了解即可。util.isArray(object)如果给定的参数 object 是一个数组返回true否则返回false。var util require(util); util.isArray([]); // true util.isArray(new Array()); // true util.isArray({}); // falseutil.isRegExp(object)如果给定的参数 object 是一个正则表达式返回true否则返回false。util.isRegExp(/some regexp/); // true util.isRegExp(new RegExp(another regexp)); // true util.isRegExp({}); // falseutil.isDate(object)如果给定的参数 object 是一个日期返回true否则返回false。util.isDate(new Date()); // true util.isDate(Date()); // false (without new returns a String) util.isDate({}); // false七、本章小结方法用途util.format()格式化字符串util.inspect()将对象转为可读字符串用于调试util.promisify()将回调函数转为 Promise推荐util.callbackify()将 Promise 转为回调函数util.inherits()实现原型继承ES6 后推荐用class/extendsutil.deprecate()标记废弃函数util.types增强的类型检测工具集提示util.promisify是日常开发中最常用的方法它让你能够将大量基于回调的 Node.js 核心模块函数转换为返回 Promise 的函数从而与async/await完美配合。在新代码中推荐使用class和extends语法替代util.inherits。