GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • 首页
  • HTML
  • JavaScript
  • CSS
  • React
  • Python3
  • Java
  • C
  • C++
  • C#
  • Go
  • SQL
  • Linux
  • VS Code

This view

  • Original page
  • New address

GeezerVison is showing www.runoob.com — Node.js 常用工具 | 菜鸟教程

菜鸟教程 -- 学的不仅是技术,更是梦想!

  • Vue3 教程
  • Vue2 教程
  • Bootstrap3
  • Bootstrap4
  • Bootstrap5
  • 机器学习
  • PyTorch
  • TensorFlow
  • Sklearn
  • NLP
  • AI Agent
  • Ollama
  • Coding Plan
Node.js 教程
Node.js 教程 Node.js 概念 Node.js 安装配置 Node.js VS Code Node.js NVM Node.js 创建第一个应用 Node.js 工作机制 NPM 使用介绍 PNPM 使用介绍 Node.js REPL Node.js 异步编程 Node.js 回调函数 Node.js Promise Node.js async/await Node.js 事件循环 Node.js EventEmitter Node.js Buffer Node.js Stream Node.js 模块系统 Node.js 模块导入 Node.js 函数 Node.js 路由 Node.js 全局对象 Node.js 常用工具 Node.js 文件系统 Node.js 内置模块 Node.js 测验

Node.js 应用

Node.js 构建简单应用 Node.js GET/POST请求 Node.js util 模块 Node.js Web 模块 Node.js Express 框架 Node.js RESTful API Node.js 多进程 Node.js JXcore 打包 Node.js MySQL Node.js MongoDB npx 入门教程
Node.js 全局对象
Node.js 文件系统

Node.js 常用工具

util 模块是 Node.js 的一个内置模块,包含了实用工具函数,用于支持 JavaScript 编程中的调试、错误处理、格式化等功能。

util 提供常用函数的集合,用于弥补核心 JavaScript 的功能过于精简的不足。

util 模块中的功能涵盖了从对象检查、继承到格式化字符串等多个方面。

导入 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包含多种类型检测方法的集合,例如 isAnyArrayBuffer、isBigInt64Array。
util.isDeepStrictEqual(val1, val2)判断两个值是否深度相等,类似于深度比较。
util.getSystemErrorName(err)根据错误码返回系统错误名称。
util.inspect.custom一个 Symbol,可以定义自定义的 inspect 行为,用于调试。

util.types 下的类型检测方法

util.types 是一个包含许多类型检测方法的集合,扩展了 JavaScript 的 typeof 和 instanceof。

方法描述
util.types.isAnyArrayBuffer(value)检查值是否为 ArrayBuffer 或 SharedArrayBuffer。
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('util');
const name = 'Alice';
const age = 25;
console.log(util.format('Name: %s, Age: %d', name, age));  // 输出: Name: Alice, Age: 25

util.promisify() - 转换回调函数为 Promise

util.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' 异常,如果没有被捕获,进程将会退出。

null 在回调函数中作为一个参数有其特殊的意义,如果回调函数的首个参数为 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
});

original 为 async 异步函数。该函数返回传统回调函数。

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.types - 数据类型检测

util.types 提供了一组方法来检测特定数据类型,扩展了 typeof 和 instanceof 的功能。

实例

const util = require('util');
console.log(util.types.isDate(new Date()));  // true
console.log(util.types.isMap(new Map()));    // true

util.inherits

util.inherits(constructor, superConstructor) 是一个实现对象间原型继承的函数。

JavaScript 的面向对象特性是基于原型的,与常见的基于类的不同。JavaScript 没有提供对象继承的语言级别特性,而是通过原型复制来实现的。

在这里我们只介绍 util.inherits 的用法,示例如下:

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(); 
objBase.sayHello(); 
console.log(objBase); 
var objSub = new Sub(); 
objSub.showName(); 
//objSub.sayHello(); 
console.log(objSub); 

我们定义了一个基础对象 Base 和一个继承自 Base 的 Sub,Base 有三个在构造函数内定义的属性和一个原型中定义的函数,通过util.inherits 实现继承。运行结果如下:

base 
Hello base 
{ name: 'base', base: 1991, sayHello: [Function] } 
sub 
{ name: 'sub' }

注意:Sub 仅仅继承了Base 在原型中定义的函数,而构造函数内部创造的 base 属 性和 sayHello 函数都没有被 Sub 继承。

同时,在原型中定义的属性不会被 console.log 作 为对象的属性输出。如果我们去掉 objSub.sayHello(); 这行的注释,将会看到:

node.js:201 
throw e; // process.nextTick error, or 'error' event on first tick 
^ 
TypeError: Object #<Sub> has no method 'sayHello' 
at Object.<anonymous> (/home/byvoid/utilinherits.js:29:8) 
at Module._compile (module.js:441:26) 
at Object..js (module.js:459:10) 
at Module.load (module.js:348:31) 
at Function._load (module.js:308:12) 
at Array.0 (module.js:479:10) 
at EventEmitter._tickCallback (node.js:192:40) 

注意:在 ES6 出现之前,util.inherits 是 Node.js 中实现继承的主要方法。但是,ES6 之后推荐使用 class 和 extends 语法,这样继承的代码更具可读性。

util.inspect() - 打印对象结构

util.inspect(object[, options]):将对象转换为字符串表示形式,便于调试。

util.inspect() 将对象转换为字符串形式,常用于调试,以查看对象的详细结构和属性。可以指定 options 参数来控制输出格式。

实例


const obj = { a: 1, b: 2, c: { d: 3 } };
console.log(util.inspect(obj, { showHidden: false, depth: null, colors: true }));

util.isArray(object)

如果给定的参数 "object" 是一个数组返回 true,否则返回 false。

var util = require('util');

util.isArray([])
  // true
util.isArray(new Array)
  // true
util.isArray({})
  // false

util.isRegExp(object)

如果给定的参数 "object" 是一个正则表达式返回true,否则返回false。

var util = require('util');

util.isRegExp(/some regexp/)
  // true
util.isRegExp(new RegExp('another regexp'))
  // true
util.isRegExp({})
  // false

util.isDate(object)

如果给定的参数 "object" 是一个日期返回true,否则返回false。

var util = require('util');

util.isDate(new Date())
  // true
util.isDate(Date())
  // false (without 'new' returns a String)
util.isDate({})
  // false

更多详情可以访问 http://nodejs.org/api/util.html 了解详细内容。

AI 思考中...
Node.js 全局对象
Node.js 文件系统

2 篇笔记 写笔记

  1. #0

       qwq

      106***[email protected]

    94

    util.inhrits() 可以继承原型方法(node 版本 V10.8.0)。

    let util = require('util');
    function Base() {
            this.name = 'name';
            this.base = 1995;
            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);
    
    let baseObj = new Base();
    console.log(baseObj);
    baseObj.showName();
    
    let subObj = new sub();
    console.log(subObj);
    console.log(subObj.name);
    subObj.showName();

    运行结果:

    Base { name: 'name', base: 1995, sayHello: [Function] }
    name
    sub { name: 'sub' }
    sub
    sub
    qwq

       qwq

      106***[email protected]

    8年前 (2019-04-03)
  2. #0

       汪磊

      151***[email protected]

    30

    新版本中 util.inhrits 废弃后的写法,直接继承即可:

    const util = require('util');
    
    async function fun() {
        return "hello world";
    }
    
    const callbackFunction = util.callbackify(fun);
    callbackFunction((err, ret) => {
        if (err) throw err;
        console.log(ret);
    })
    
    class Base{
        name = 'base';
        base = 1991;
        sayHello = function() {
            console.log('Hello ' + this.name);
        }
    }
    
    Base.prototype.showName = function() {
        console.log(this.name);
    }
    
    class Sub extends Base {
        name = 'sub';
    }
    
    var objBase = new Base();
    objBase.showName();
    objBase.sayHello();
    console.log(objBase);
    var objSub = new Sub();
    objSub.showName();
    objSub.sayHello();
    console.log(objSub);
    汪磊

       汪磊

      151***[email protected]

    5年前 (2022-05-10)

点我分享笔记

取消

  • 昵称 (必填)
  • 邮箱 (必填)
  • 引用地址
分类导航
  • Python / 数据科学
    • Python 教程
    • Python2.x 教程
    • FastAPI 教程
    • Flask 教程
    • Django 教程
    • NumPy 教程
    • Pandas 教程
    • SciPy 教程
    • Matplotlib 教程
    • Dash 教程
    • Jupyter Notebook 教程
    • Pillow 教程
    • 量化交易
    • R 教程
    • Julia 教程
  • AI / 智能开发
    • AI Agent(智能体)
    • AI(人工智能)
    • AI 应用案例
    • Codex 教程
    • Vibe Coding 教程
    • Claude Code
    • OpenCode
    • Skills(技能)
    • Ollama 教程
    • Hermes Agent
    • DeepSeek Harness
    • Pi Agent
    • AI 数学基础
    • TensorFlow 教程
    • PyTorch 教程
    • Scikit-learn 教程
    • 机器 教程
    • LangChain
    • 自然语言处理 NLP
    • OpenCV 教程
    • Selenium 教程
    • Playwright 教程
  • 前端开发
    • HTML 教程
    • HTML5 教程
    • CSS 教程
    • CSS3 教程
    • JavaScript 教程
    • HTML DOM 教程
    • TypeScript 教程
    • AJAX 教程
    • JSON 教程
    • Tailwind CSS 教程
    • Bootstrap4 教程
    • Bootstrap5 教程
    • Foundation 教程
    • Vue.js 教程
    • Vue3 教程
    • React 教程
    • Next.js 教程
    • Three.js 教程
    • AngularJS 教程
    • Angular 教程
    • jQuery 教程
    • jQuery UI 教程
    • jQuery EasyUI 教程
    • ECharts 教程
    • Chart.js 教程
    • Highcharts 教程
    • Google 地图 教程
    • SVG 教程
    • Font Awesome 教程
  • 后端开发
    • Node.js 教程
    • Electron 教程
    • PHP 教程
    • Java 教程
    • Go 教程
    • Rust 教程
    • C# 教程
    • Unity 教程
    • Servlet 教程
    • JSP 教程
    • ASP 教程
    • AppML 教程
    • VBScript 教程
    • Swagger 教程
    • RESTful API 教程
    • Docker 教程
    • Linux 教程
    • ZooKeeper 教程
  • 数据库
    • SQL 教程
    • MySQL 教程
    • PostgreSQL 教程
    • SQLite 教程
    • MongoDB 教程
    • Redis 教程
    • Memcached 教程
  • 移动开发
    • Android 教程
    • Flutter 教程
    • Ionic 教程
    • jQuery Mobile 教程
    • Swift 教程
    • Kotlin 教程
  • DevOps / 工程化
    • Git 教程
    • SVN 教程
    • CMake 教程
    • Maven 教程
    • VS Code 教程
    • Obsidian 教程
    • PyCharm 教程
    • Eclipse 教程
    • Markdown 教程
    • LaTeX 教程
  • 编程语言
    • C 教程
    • C++ 教程
    • Zig 教程
    • Scala 教程
    • Ruby 教程
    • Perl 教程
    • Lua 教程
    • Dart 教程
    • 汇编语言 教程
    • Verilog 教程
  • 计算机基础
    • 计算机组成原理
    • 数据结构与算法
    • C 语言数据结构与算法
    • 设计模式
    • Python 设计模式
    • 正则表达式
    • HTTP 教程
    • TCP/IP 教程
    • 网络协议
    • W3C 教程
  • XML / Web Service
    • XML 教程
    • DTD 教程
    • XML DOM 教程
    • XSLT 教程
    • XPath 教程
    • XQuery 教程
    • XLink 教程
    • XPointer 教程
    • XML Schema 教程
    • XSL-FO 教程
    • Web Service 教程
    • WSDL 教程
    • SOAP 教程
    • RSS 教程
    • RDF 教程
  • .NET
    • ASP.NET 教程
    • MVC 教程
    • Razor 教程
    • Web Forms 教程
    • Web Pages 教程
    • PowerShell 教程
  • 网站建设
    • 网站建设指南
    • 浏览器信息
    • 网站主机教程
    • 网站品质

字节 Coding Plan 限时 9.9 元起,支持 Deepseek-V4、GLM-5.3、Doubao-Seed-Evolving、Kimi-K3。
百度 Dumate 百度推出的桌面级 AI 智能体。 输入激活码送 4000 积分
使用文档
Trae AI 原生开发环境,让编程更高效。新用户注册赠2500积分,管理项目,也交付成果。
Advertisement
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.