util模块的引入
const { format,promisify,log } = require('util');
util模块方法
目前个人比较多用的有以下方法util.format(),util.log(),util.promisify(),其余的方法或者废弃(例如util.inspect)或者不常用故不赘述。
util.format(format[, ...args])
接口作用:根据第一个参数,返回一个格式化的字符串。 参数:第一个参数为一个包含零至多个占位符的字符串,每个占位符都以%开头,类似printf的格式字符串。其中符合规范的占位符有以下几个:
%s : 指定字符串
%d : 指定一个数值
%j : 指定一个JSON可转换为字符串的对象
% : 如果%后保留为空,则不作为占位符。
具体效果和注意事项请参考以下代码演示
示例代码:
转换效果,注意,当有比占位符更多的参数时,多余的参数被转换为字符串,然后用空格分隔符连接起来 单纯一个%不会被转换
const json = {'aaa':'123'};
const allformat = format('%s:%d %j %','Name',1234567,json,'为空不显示');
console.log(allformat);
返回:
PS E:\项目\nodejs> node util.js
Name:1234567 {"aaa":"123"} % 为空不显示
如果第一个参数中的占位符找不到与之对应的参数, 那么这个占位符将不会被替换
const whileLessPlaceHolder = format('%s:%s', 'foo');
console.log(whileLessPlaceHolder);
返回:
PS E:\项目\nodejs> node util.js
foo:%s
如果第一个参数不是一个格式化字符串,那么util.format()把每个参数都转换为字符串,用空格分隔符将其连接在一起,然后返回连接后的字符串
const whileNotFormat = format(1,2,3);
console.log(whileNotFormat);
返回:
PS E:\项目\nodejs> node util.js
1 2 3
util.log(string)
接口作用:用于在控制台输出,输出带有时间戳。 参数:参数为要打印的字符串。
示例代码:
log('log输出');
返回:
PS E:\项目\nodejs> node util.js
28 Jun 22:09:37 - log输出
util.promisify(original)
接口作用:让一个异步函数返回一个promise对象,换言之,可以通过此方法,来实现异步转同步。 参数:一个异步函数。
示例代码:
const readFileFunc = async() => {
let data;
try{
data = await readFile('./index.html');
console.log("通过async/await执行");
console.log(data);
}
catch(e){
console.log(e);
}
}
readFileFunc();
const readFile = promisify(fs.readFile);
readFile("./index.html").then(data => {
console.log("通过Promise执行");
console.log(data);
}).catch(e => {
console.log("error!")
})
返回:
PS E:\项目\nodejs> node util.js
通过Promise执行
<Buffer 3c 21 44 4f 43 54 59 50 45 20 68 74 6d 6c 3e 0d 0a 3c 68 74 6d 6c 20 6c 61 6e 67 3d 22 65 6e 22 3e 0d 0a 3c 68 65 61 64 3e 0d 0a 20 20 20 20 3c 6d 65 ... >
通过async/await执行
<Buffer 3c 21 44 4f 43 54 59 50 45 20 68 74 6d 6c 3e 0d 0a 3c 68 74 6d 6c 20 6c 61 6e 67 3d 22 65 6e 22 3e 0d 0a 3c 68 65 61 64 3e 0d 0a 20 20 20 20 3c 6d 65 ... >