在 Node.js 中,util
模块提供了一系列实用工具函数,这些函数可以帮助开发者更方便地进行开发工作。下面将详细介绍 util
模块中一些常用的工具函数,并通过示例代码进行演示。
util.format()
util.format()
函数用于格式化字符串,类似于 printf
风格的格式化。它可以根据传入的参数将占位符替换为实际的值。
util.format(format[,...args])
const util = require('util');
// 格式化字符串
const message = util.format('Hello, %s! You are %d years old.', 'John', 30);
console.log(message);
在上述代码中,%s
是字符串占位符,%d
是数字占位符。util.format()
函数将 'John'
替换 %s
,将 30
替换 %d
,最终输出格式化后的字符串。
util.inherits()
util.inherits()
函数用于实现原型式继承,允许一个构造函数继承另一个构造函数的原型属性。
util.inherits(constructor, superConstructor)
const util = require('util');
function Parent() {
this.name = 'Parent';
}
Parent.prototype.sayHello = function() {
console.log(`Hello from ${this.name}`);
};
function Child() {
Parent.call(this);
this.name = 'Child';
}
util.inherits(Child, Parent);
const child = new Child();
child.sayHello();
在上述代码中,Child
构造函数继承了 Parent
构造函数的原型属性。通过 util.inherits(Child, Parent)
实现了原型式继承,使得 Child
实例可以调用 Parent
原型上的 sayHello
方法。
util.promisify()
util.promisify()
函数用于将一个遵循错误优先的回调风格的函数转换为返回 Promise 的函数。
util.promisify(original)
const util = require('util');
const fs = require('fs');
// 将 fs.readFile 转换为返回 Promise 的函数
const readFilePromise = util.promisify(fs.readFile);
readFilePromise('example.txt', 'utf8')
.then(data => {
console.log(data);
})
.catch(err => {
console.error(err);
});
在上述代码中,util.promisify(fs.readFile)
将 fs.readFile
函数转换为返回 Promise 的函数。这样就可以使用 then
和 catch
方法来处理异步操作的结果和错误。
util.inspect()
util.inspect()
函数用于将对象转换为字符串,方便调试时查看对象的详细信息。
util.inspect(object[, options])
const util = require('util');
const person = {
name: 'John',
age: 30,
address: {
city: 'New York',
street: '123 Main St'
}
};
const personString = util.inspect(person, { depth: null });
console.log(personString);
在上述代码中,util.inspect(person, { depth: null })
将 person
对象转换为字符串,并设置 depth
为 null
,表示递归打印对象的所有层级。
函数名 | 功能 | 示例 |
---|---|---|
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 开发,处理字符串格式化、继承、异步操作和调试等任务。