Nodejs utils 模块是实际开发过程中比较重要的一个模块, 在nodejs 的开发过程中比较经常的会使用到。 nodejs22马上发布在即,因此回顾一下utils 模块的相关函数和API,便于在后续的项目当中使用到。
- utils.callbackify 将函数改变为错误优先输出的callback 函数
采用
async函数(或返回Promise的函数)并返回遵循错误优先回调风格的函数。
const util = require('node:util');
async function fn() { // 此时函数必须是异步函数 或者能够返回promise的函数
return 'hello world';
}
const callbackFunction = util.callbackify(fn);
callbackFunction((err, ret) => {
if (err) throw err;
console.log(ret);
});
- utils.format 函数 常用于格式化打印字符串 如果参数不包含有效的格式说明符,则返回所有的参数组成的串联的字符串。
const a = util.format('%s:%s', 'foo');
console.log(a);
// Returns: 'foo:%s'
- util.getSystemErrorName 返回来着Nodejs的数字错误码的字符串名称。
fs.access('file/that/does/not/exist', (err) => {
const name = util.getSystemErrorName(err.errno);
console.error(name); // ENOENT
});
// ENOENT
-
util.inherits() 该方法使用inherits来实现es6的继承,但是目前已经不推荐使用,官方建议还是使用之前的es6语法关键字extends来实现继承关系。
-
utils.inspect 该函数和JSON.stringfy比较类似都可以用来将一个对象进行字符串化。但是前者机制比较灵活,可以通过传入的options来改变输出的结果。 同时还可以改变输出的格式和颜色。
class Foo {
get [Symbol.toStringTag]() {
return 'bar';
}
}
class Bar {}
const baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } });
util.inspect(new Foo()); // 'Foo [bar] {}'
util.inspect(new Bar()); // 'Bar {}'
util.inspect(baz); // '[foo] {}'
-
util.isDeepStrictEqual(val1, val2) 用于比较v1和v2两个值是否是深度严格相等的。类似于assert模块的
assert.deepStrictEqual(v1, v2)如果是严格相等的返回true 否则返回false。 -
util.parseArgs([config]) 函数 命令行参数解析相关的API,提供类似于process.argv等类似的功能,但是更加强大。 可以提供类似于简写相关的参数。
eg:
const { parseArgs } = require('node:util');
const options = {
'color': { type: 'boolean' },
'no-color': { type: 'boolean' },
'logfile': { type: 'string' },
'no-logfile': { type: 'boolean' },
};
const { values, tokens } = parseArgs({ options, tokens: true });
// Reprocess the option tokens and overwrite the returned values.
tokens
.filter((token) => token.kind === 'option')
.forEach((token) => {
if (token.name.startsWith('no-')) {
// Store foo:false for --no-foo
const positiveName = token.name.slice(3);
values[positiveName] = false;
delete values[token.name];
} else {
// Resave value so last one wins if both --foo and --no-foo.
values[token.name] = token.value ?? true;
}
});
const color = values.color;
const logfile = values.logfile ?? 'default.log';
console.log({ logfile, color });
util.promisify将callback 形式的错误优先的回调函数变为promise类型的函数。 只适用于将(err, value) => ...回调作为最后一个参数来表示的callback 回调函数。
const util = require('node:util');
const fs = require('node:fs');
const stat = util.promisify(fs.stat);
stat('.').then((stats) => {
// Do something with `stats`
}).catch((error) => {
// Handle the error.
});
- utils 的TextDeCoder的实现,用于编解码字符串传输时比较好用。同时还有
util.TextEncoder用于字符串编码。还有options等选项用于支持编码格式编码错误等选项。
const decoder = new TextDecoder();
const u8arr = new Uint8Array([72, 101, 108, 108, 111]);
console.log(decoder.decode(u8arr)); // Hello
将字符串编码为unit8Array二进制数组。
const encoder = new TextEncoder();
const uint8array = encoder.encode('this is some data');
// 编码后的二进制数组
Uint8Array(17) [
116, 104, 105, 115, 32,
105, 115, 32, 115, 111,
109, 101, 32, 100, 97,
116, 97
]
textEncoder.encodeInto(src, dest) 该方法用于编码字符串,但同时支持读和写入字符串数组的对象。
const encoder = new TextEncoder();
const src = 'this is some data';
const dest = new Uint8Array(10);
const { read, written } = encoder.encodeInto(src, dest);
- utils.isType 可通过
require('node:util').types或require('node:util/types')访问。该方法能够为不同类型的对象提供类型检查。 例如:Date RegExp Promise Proxy Set Map WeakMap ArrayBuffer WeakMap 等。