Node.js-核心模块之util模块

util 模块是 Node.js 核心模块之一,提供了一组实用工具函数,用于处理不同类型的数据和操作。以下是 util 模块的主要内容和使用方法的详细解释:

1. util.promisify(original):

  • util.promisify(original) 将使用回调风格的函数(通常是Node.js标准库的函数)转换为返回 Promise 的函数。

    const util = require('util');
    const fs = require('fs');
    
    // 使用回调的方式读取文件
    fs.readFile('file.txt', 'utf8', (err, data) => {
      if (err) throw err;
      console.log(data);
    });
    
    // 使用 promisify 转换为返回 Promise 的方式
    const readFilePromise = util.promisify(fs.readFile);
    
    // 使用 Promise 的方式读取文件
    readFilePromise('file.txt', 'utf8')
      .then(data => {
        console.log(data);
      })
      .catch(err => {
        console.error(err);
      });
    

2. util.inherits(constructor, superConstructor):

  • util.inherits(constructor, superConstructor) 通过原型继承的方式继承一个构造函数的原型。

    const util = require('util');
    
    function Animal(name) {
      this.name = name;
    }
    
    Animal.prototype.sayHello = function() {
      console.log(`Hello, I'm ${this.name}`);
    };
    
    function Dog(name) {
      // 调用父类构造函数
      Animal.call(this, name);
    }
    
    // 继承 Animal 的原型
    util.inherits(Dog, Animal);
    
    const myDog = new Dog('Buddy');
    myDog.sayHello(); // Hello, I'm Buddy
    

3. util.inspect(object[, options]):

  • util.inspect(object[, options]) 将对象转换为字符串,通常用于调试目的。

    const util = require('util');
    
    const obj = {
      name: 'John',
      age: 30,
      address: {
        city: 'New York',
        country: 'USA'
      }
    };
    
    console.log(util.inspect(obj, { depth: null }));
    

4. util.format(format[, …args]):

  • util.format(format[, ...args]) 格式化字符串,类似于 printf

    const util = require('util');
    
    const name = 'John';
    const age = 30;
    
    const message = util.format('Name: %s, Age: %d', name, age);
    console.log(message); // Name: John, Age: 30
    

5. util.promisify.custom:

  • util.promisify.custom 一个 Symbol,用于定义一个对象的自定义 promisify 方法。

    const util = require('util');
    const fs = require('fs');
    
    const customPromisify = Symbol('customPromisify');
    
    fs.readFile[util.promisify.custom] = (filename, encoding) => {
      return new Promise((resolve, reject) => {
        fs.readFile(filename, encoding, (err, data) => {
          if (err) reject(err);
          else resolve(data);
        });
      });
    };
    
    const readFilePromise = util.promisify(fs.readFile);
    
    readFilePromise('file.txt', 'utf8')
      .then(data => {
        console.log(data);
      })
      .catch(err => {
        console.error(err);
      });
    

6. 其他实用函数

  • util.deprecate(fn, message) 返回一个函数,该函数会在调用时打印 message 提示。通常用于标记废弃的函数。

    const util = require('util');
    
    function deprecatedFunction() {
      console.log('This function is deprecated.');
    }
    
    const deprecatedFunctionWithMessage = util.deprecate(deprecatedFunction, 'This function is deprecated. Use the newFunction instead.');
    
    deprecatedFunctionWithMessage(); // 输出提示信息
    

这只是 util 模块的一部分功能。util 模块包含了许多其他实用函数,具体的使用取决于你的应用程序的需求。你可以在 Node.js 官方文档 中找到详细的文档。

  • 26
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

[猫玖]

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值