nodejs 模块之 util 模块 util 模块是一些工具函数,来补充 nodejs 的 API,常见模块有如下 把 async 或者返回 promise 的转成回调函数异步类型 把回调函数转成 promise 形式 占位符替换 对对象进行格式化操作,并提供个性化方法 提供一些类型的判断 总结 util 常用的一个模块我觉得应该是将回调函数转成 promise 形式,因为 nodejs 有好多…

nodejs 模块之 util 模块

util 模块是一些工具函数,来补充 nodejs 的 API,常见模块有如下

  • 把 async 或者返回 promise 的转成回调函数异步类型
async function fn() {
  return "hello fn";
}
const callbackFn = util.callbackify(fn);

callbackFn((err, ret) => {
  console.log(ret);
});

function fn2() {
  return Promise.resolve("hello fn2");
}
const callbackFn2 = util.callbackify(fn2);
callbackFn2((err, ret) => {
  console.log(ret);
});
  • 把回调函数转成 promise 形式
// 回调函数形式的读取文件
const fs = require("fs");
fs.readFile("./demo01.js", (err, data) => {
  if (err) {
    return;
  }
  console.log(data.toString());
});

const util = require("util");
// 转成promise
const readFilePromise = util.promisify(fs.readFile);
readFilePromise("./demo01.js").then(
  (data) => {
    console.log(data.toString());
  },
  (err) => {
    console.log(err);
  }
);
  • 占位符替换
const util = require("util");
const format = util.format("%s,%s", "hello", "world");
console.log(format);
  • 对对象进行格式化操作,并提供个性化方法
const util = require("util");
const object = {
  key1: ["v1", "v2", ["v3"]],
  key2: "v4",
  key3: new Array(1, 2, 3)
};
// compact:是否独占一行
// depth:显示层级 默认是2
// breakLength :超出多行换行

console.log(util.inspect(object, { compact: true, depth: 2, breakLength: 20 }));
  • 提供一些类型的判断
// util一些类型的判断
const util = require("util");
// 是否是正则
let a = util.isRegExp(/some regexp/);
// 是否是日期
let b = util.isDate(new Date());
// 是否是error
let c = util.isError(new Error());
// 是否是数组
let d = util.isArray([]);
console.log(a, b, c, d);

总结

  • util 常用的一个模块我觉得应该是将回调函数转成 promise 形式,因为 nodejs 有好多 API 都是异步回调形式,转成 promise 比较方便。

暂无评论