微信登录

核心模块 - util 模块 - 常用工具函数

Node.js 《核心模块 - util 模块 - 常用工具函数》

在 Node.js 中,util 模块提供了一系列实用工具函数,这些函数可以帮助开发者更方便地进行开发工作。下面将详细介绍 util 模块中一些常用的工具函数,并通过示例代码进行演示。

1. util.format()

功能

util.format() 函数用于格式化字符串,类似于 printf 风格的格式化。它可以根据传入的参数将占位符替换为实际的值。

语法

  1. util.format(format[,...args])

示例代码

  1. const util = require('util');
  2. // 格式化字符串
  3. const message = util.format('Hello, %s! You are %d years old.', 'John', 30);
  4. console.log(message);

解释

在上述代码中,%s 是字符串占位符,%d 是数字占位符。util.format() 函数将 'John' 替换 %s,将 30 替换 %d,最终输出格式化后的字符串。

2. util.inherits()

功能

util.inherits() 函数用于实现原型式继承,允许一个构造函数继承另一个构造函数的原型属性。

语法

  1. util.inherits(constructor, superConstructor)

示例代码

  1. const util = require('util');
  2. function Parent() {
  3. this.name = 'Parent';
  4. }
  5. Parent.prototype.sayHello = function() {
  6. console.log(`Hello from ${this.name}`);
  7. };
  8. function Child() {
  9. Parent.call(this);
  10. this.name = 'Child';
  11. }
  12. util.inherits(Child, Parent);
  13. const child = new Child();
  14. child.sayHello();

解释

在上述代码中,Child 构造函数继承了 Parent 构造函数的原型属性。通过 util.inherits(Child, Parent) 实现了原型式继承,使得 Child 实例可以调用 Parent 原型上的 sayHello 方法。

3. util.promisify()

功能

util.promisify() 函数用于将一个遵循错误优先的回调风格的函数转换为返回 Promise 的函数。

语法

  1. util.promisify(original)

示例代码

  1. const util = require('util');
  2. const fs = require('fs');
  3. // 将 fs.readFile 转换为返回 Promise 的函数
  4. const readFilePromise = util.promisify(fs.readFile);
  5. readFilePromise('example.txt', 'utf8')
  6. .then(data => {
  7. console.log(data);
  8. })
  9. .catch(err => {
  10. console.error(err);
  11. });

解释

在上述代码中,util.promisify(fs.readFile)fs.readFile 函数转换为返回 Promise 的函数。这样就可以使用 thencatch 方法来处理异步操作的结果和错误。

4. util.inspect()

功能

util.inspect() 函数用于将对象转换为字符串,方便调试时查看对象的详细信息。

语法

  1. util.inspect(object[, options])

示例代码

  1. const util = require('util');
  2. const person = {
  3. name: 'John',
  4. age: 30,
  5. address: {
  6. city: 'New York',
  7. street: '123 Main St'
  8. }
  9. };
  10. const personString = util.inspect(person, { depth: null });
  11. console.log(personString);

解释

在上述代码中,util.inspect(person, { depth: null })person 对象转换为字符串,并设置 depthnull,表示递归打印对象的所有层级。

总结

函数名 功能 示例
util.format() 格式化字符串 util.format('Hello, %s!', 'John')
util.inherits() 实现原型式继承 util.inherits(Child, Parent)
util.promisify() 将回调风格函数转换为返回 Promise 的函数 util.promisify(fs.readFile)
util.inspect() 将对象转换为字符串 util.inspect(person, { depth: null })

通过使用 util 模块中的这些常用工具函数,开发者可以更高效地进行 Node.js 开发,处理字符串格式化、继承、异步操作和调试等任务。