nodejs -- util

Node.js 提供的 util 模块是一个包含实用工具函数的模块,用于开发过程中常见的功能。它提供了许多在处理对象、字符串、函数等时常用的工具函数。
常用的 util 模块功能
首先,我们需要导入 util 模块:
const util = require('util');

1. util.format

util.format 类似于 printf 风格的格式化功能。它将格式字符串和一系列参数合并成一个字符串,类似于 JavaScript 的 console.log。
示例:
const name = 'Alice';
const age = 25;

const formattedString = util.format('My name is %s and I am %d years old.', name, age);
console.log(formattedString);
// 输出: My name is Alice and I am 25 years old.

格式化符号:

1.%s:字符串
2.%d:数字(会转换为整数)
3.%j:JSON(会将对象转换为 JSON 字符串)
4.%O:对象(以开发者友好的格式显示对象)
5.%f:浮动数字(小数)

2. util.inspect

util.inspect 函数返回一个对象的字符串表示,它是调试时非常有用的工具。它允许自定义对象如何被打印出来,支持很多参数,例如 depth 和 colors。
示例:

const obj = {
  name: 'Alice',
  age: 25,
  greet: function() {
	console.log('Hello');
  }
};
const inspected = util.inspect(obj, { showHidden: false, depth: 2, colors: true });
console.log(inspected);

这将打印出对象的详细信息,depth 参数控制对象嵌套的深度,colors 参数决定是否使用颜色高亮输出。
image

3. util.promisify

util.promisify 用于将基于回调的 API 转换为返回 Promise 的函数。这个功能非常适合将回调风格的 API(如 Node.js 的许多内置模块)转换为 Promise 风格,从而支持 async/await 语法。
示例:

const fs = require('fs');
const util = require('util');

// 将 fs.readFile 转换为返回 Promise 的版本
const readFileAsync = util.promisify(fs.readFile);

readFileAsync('example.txt', 'utf-8')
  .then(data => {
	console.log('File contents:', data);
  })
  .catch(err => {
	console.error('Error reading file:', err);
  });

4. util.deprecate

util.deprecate 用于标记一个 API 为弃用(deprecated),并给出警告。它接收两个参数:一个是要弃用的函数,另一个是弃用的警告信息。
示例:

const util = require('util');

// 标记一个函数为弃用
const deprecatedFunction = util.deprecate(function() {
  console.log('This function is deprecated!');
}, 'deprecatedFunction is deprecated. Please use newFunction instead.');

deprecatedFunction(); // 调用时会显示警告信息

image

5. util.inherits

util.inherits 是用于实现类继承的工具函数,虽然现在 ES6 的 class 语法已经被广泛使用,但 util.inherits 仍然是一个有用的工具,特别是处理一些传统的 JavaScript 继承时。
示例:
const util = require('util');

// 基类
function Animal(name) {
  this.name = name;
}

Animal.prototype.sayHello = function() {
  console.log(`Hello, I am ${this.name}`);
};

// 子类
function Dog(name, breed) {
  Animal.call(this, name); // 继承 Animal 的属性
  this.breed = breed;
}

// 使用 util.inherits 实现继承
util.inherits(Dog, Animal);

const dog = new Dog('Max', 'Golden Retriever');
dog.sayHello();  // 输出: Hello, I am Max

6. util.callbackify

util.callbackify 是 util.promisify 的反向操作,它将一个返回 Promise 的函数转换为使用回调的函数。
示例:

const util = require('util');

// 一个返回 Promise 的函数
async function asyncFunc() {
  return 'Hello from async!';
}

// 将返回 Promise 的函数转换为使用回调的函数
const callbackFunc = util.callbackify(asyncFunc);

// 使用回调函数调用
callbackFunc((err, result) => {
  if (err) {
	console.error('Error:', err);
  } else {
	console.log('Result:', result);
  }
});
posted @ 2025-04-07 14:24  蜗牛般庄  阅读(46)  评论(0)    收藏  举报
Title
页脚 HTML 代码