Node.js 常用工具

util 模块里真正会用到的那几个:promisify、inspect、format、types。

Intermediate
Key Points`util` 是 Node 的杂物间,`promisify` 和 `inspect` 是里面最值钱的两件。

promisify

JavaScript
const util = require('node:util');
const fs = require('node:fs');

const readFile = util.promisify(fs.readFile);
const data = await readFile('package.json', 'utf8');
console.log(JSON.parse(data).name);
Output
demo

Works only for error-first callbacks. When the callback yields multiple values (like fs.read), promisify keeps only the first.

inspect

JavaScript
const util = require('node:util');

const obj = { a: 1, b: { c: [1, 2, 3] }, d: new Map([['k', 'v']]) };

console.log(util.inspect(obj));
console.log(util.inspect(obj, { depth: 0, colors: false, compact: true }));

// 深度对比
console.log(util.isDeepStrictEqual({ a: [1] }, { a: [1] }));
Output
{ a: 1, b: { c: [ 1, 2, 3 ] }, d: Map(1) { 'k' => 'v' } }
{ a: 1, b: [Object], d: Map(1) {} }
true

console.log formats objects with util.inspect internally. For deeper nesting or colour control, call inspect with options.

format 与 占位符

JavaScript
const util = require('node:util');

console.log(util.format('%s 有 %d 个文件,占 %o', 'dir', 3, { ok: true }));
console.log(util.format('%j', { a: 1 }));
Output
dir 有 3 个文件,占 { ok: true }
{"a":1}
PlaceholderMeaning
%s字符串
%d数字
%i整数
%f浮点
%jJSON
%o / %O对象(%O 不截断)
%cCSS,浏览器端才有用

types 与 其他

JavaScript
const { types } = require('node:util');

console.log(types.isPromise(Promise.resolve()));
console.log(types.isDate(new Date()));
console.log(types.isRegExp(/a/));

const { TextDecoder } = require('node:util');
console.log(new TextDecoder('utf-8').decode(Buffer.from('你好')));
Output
true
true
true
你好
Do not test promises with x instanceof Promise — it fails across realms (vm, workers). util.types.isPromise is reliable.

Friends & Partners