util 模块

1.util.callbackify(original)

original <Function>  async 异步函数。
返回: <Function> 传统回调函数。

将 async 异步函数(或者一个返回值为 Promise 的函数)转换成遵循异常优先的回调风格的函数,例如将 (err, value) => ... 回调作为最后一个参数。 在回调函数中,第一个参数为拒绝的原因(如果 Promise 解决,则为 null),第二个参数则是解决的值。

const util = require('util');

async function fn() {
  return 'hello world';
}
const callbackFunction = util.callbackify(fn);

callbackFunction((err, ret) => {
  if (err) throw err;
  console.log(ret);
});

 输出:

hello world

回调函数是异步执行的,并且有异常堆栈错误追踪。 如果回调函数抛出一个异常,进程会触发一个 'uncaughtException' 异常,如果没有被捕获,进程将会退出。

null 在回调函数中作为一个参数有其特殊的意义,如果回调函数的首个参数为 Promise 拒绝的原因且带有返回值,且值可以转换成布尔值 false,这个值会被封装在 Error 对象里,可以通过属性 reason 获取。

function fn() {
  return Promise.reject(null);
}
const callbackFunction = util.callbackify(fn);

callbackFunction((err, ret) => {
  // 当 Promise 被以 `null` 拒绝时,它被包装为 Error 并且原始值存储在 `reason` 中。
  err && err.hasOwnProperty('reason') && err.reason === null;  // true
});

为什么可以使用err和ret???

2.util.debuglog(section)

section <string> 一个字符串,指定要为应用的哪些部分创建 debuglog 函数。
返回: <Function> 日志函数。

util.debuglog() 方法用于创建一个函数,基于 NODE_DEBUG 环境变量的存在与否有条件地写入调试信息到 stderr。 如果 section 名称在环境变量的值中,则返回的函数类似于 console.error()。 否则,返回的函数是一个空操作。

const util = require('util');
const debuglog = util.debuglog('foo');

debuglog('hello from foo [%d]', 123);

输出:

如果程序在环境中运行时带上 NODE_DEBUG=foo,则输出类似如下:

FOO 3245: hello from foo [123]

 

const util = require('util');
const debuglog = util.debuglog('foo-bar');

debuglog('hi there, it\'s foo-bar [%d]', 2333);

 

如果在环境中使用 NODE_DEBUG=foo* 运行,那么它将输出如下内容:

FOO-BAR 3257: hi there, it's foo-bar [2333]
NODE_DEBUG 环境变量中可指定多个由逗号分隔的 section 名称。 例如:NODE_DEBUG=fs,net,tls。

3.util.deprecate(fn, msg[, code])

fn <Function> 要被废弃的函数。
msg <string> 当调用废弃的函数时显示的警告消息。
code <string> 废弃码。 有关代码列表,请参阅废弃的 API 列。
返回: <Function> 废弃的函数被包装以发出警告。
util.deprecate() 方法以一种标记为已废弃的方式包装 fn(可以是函数或类)。

 

const util = require('util');

exports.obsoleteFunction = util.deprecate(() => {
  // 一些操作。
}, 'obsoleteFunction() 已废弃,使用 newShinyFunction() 代替');

当被调用时, util.deprecate() 会返回一个函数,这个函数会使用 'warning' 事件触发一个 DeprecationWarning。 默认情况下,警告只在首次被调用时才会被触发并打印到 stderr。 警告被触发之后,被包装的函数会被调用。

如果在对 util.deprecate() 的多次调用中提供了相同的可选 code,则该 code 仅触发一次警告。

 

const util = require('util');

const fn1 = util.deprecate(someFunction, someMessage, 'DEP0001');
const fn2 = util.deprecate(someOtherFunction, someOtherMessage, 'DEP0001');
fn1(); // 使用代码 DEP0001 触发废弃警告。
fn2(); // 不会触发废弃警告,因为它具有相同的代码。

如果使用了 --no-deprecation 或 --no-warnings 命令行标记,或 process.noDeprecation 属性在首次废弃警告之前被设为 true,则 util.deprecate() 方法什么也不做。

如果设置了 --trace-deprecation 或 --trace-warnings 命令行标记,或 process.traceDeprecation 属性被设为 true,则废弃的函数首次被调用时会把警告与堆栈追踪打印到 stderr

如果设置了 --throw-deprecation 命令行标记,或 process.throwDeprecation 属性被设为 true,则当废弃的函数被调用时会抛出一个异常。

--throw-deprecation 命令行标记和 process.throwDeprecation 属性优先于 --trace-deprecation 和 process.traceDeprecation

 

4.util.format(format[, ...args])

format <string> 一个类似 printf 的格式字符串。
util.format() 方法返回一个格式化后的字符串,使用第一个参数作为一个类似 printf 的格式的字符串,该字符串可以包含零个或多个格式占位符。 每个占位符会被对应参数转换后的值所替换。 支持的占位符有:

%s - String 将用于转换除 BigInt、 Object 和 -0 外的所有值。BigInt 值将用 n 表示,而没有用户定义 toString 函数的对象使用带有选项 { depth: 0, colors: false, compact: 3 } 的 util.inspect() 进行检查。
%d - Number 将用于转换除 BigInt 和 Symbol 之外的所有值。
%i - parseInt(value, 10) 用于除 BigInt 和 Symbol 之外的所有值。
%f - parseFloat(value) 用于除 BigInt 和 Symbol 之外的所有值。
%j - JSON。如果参数包含循环引用,则替换为字符串 '[Circular]'。
%o - Object。具有通用 JavaScript 对象格式的对象的字符串表示形式。 类似于带有选项 { showHidden: true, showProxy: true } 的 util.inspect()。 这将显示完整对象,包括非可枚举属性和代理。
%O - Object。具有通用 JavaScript 对象格式的对象的字符串表示形式。 类似于 util.inspect() 但没有选项。 这将显示完整对象,不包括非可枚举属性和代理。
%c - CSS。该说明符当前会被忽略,将会跳过任何传入的 CSS。
%% - 单个百分号('%')。这不会消耗参数。
返回: <string> 格式化的字符串。
util.format('%s:%s', 'foo');
// 返回: 'foo:%s'

如果类型不是 string,则使用 util.inspect() 格式化不属于格式字符串的值。

如果传入 util.format() 方法的参数比占位符的数量多,则多出的参数会被强制转换为字符串,然后拼接到返回的字符串,参数之间用一个空格分隔。

 

util.format('%s:%s', 'foo', 'bar', 'baz');
// 返回: 'foo:bar baz'

 util.format() 是一种用作调试工具的同步方法。 某些输入值可能会产生严重的性能开销,从而阻止事件循环。 请谨慎使用此功能,切勿在热代码路径中使用。

5.util.formatWithOptions(inspectOptions, format[, ...args])

inspectOptions <对象>
format <string>
此函数与相同util.format(),不同之处在于它接受inspectOptions指定传递给的选项的参数 util.inspect()。
util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 });
// Returns 'See object { foo: 42 }', where `42` is colored as a number
// when printed to a terminal.

 

6.util.getSystemErrorName(err)

返回来自Node.js API的数字错误代码的字符串名称。错误代码和错误名称之间的映射取决于平台。有关常见错误的名称,请参见“ 常见系统错误 ”。

fs.access('file/that/does/not/exist', (err) => {
  const name = util.getSystemErrorName(err.errno);
  console.error(name);  // ENOENT
});

7.util.inherits(constructor, superConstructor)

constructor <功能>
superConstructor <功能>
不建议使用 util.inherits()。 请使用 ES6 的 class 和 extends 关键词获得语言层面的继承支持。 这两种方式是语义上不兼容的。

从一个构造函数中继承原型方法到另一个。 constructor 的原型会被设置到一个从 superConstructor 创建的新对象上。
const util = require('util');
const EventEmitter = require('events');

function MyStream() {
  EventEmitter.call(this);
}

util.inherits(MyStream, EventEmitter);

MyStream.prototype.write = function(data) {
  this.emit('data', data);
};

const stream = new MyStream();

console.log(stream instanceof EventEmitter); // true
console.log(MyStream.super_ === EventEmitter); // true

stream.on('data', (data) => {
  console.log(`接收的数据:"${data}"`);
});
stream.write('运作良好!'); // 接收的数据:"运作良好!"

 

const EventEmitter = require('events');

class MyStream extends EventEmitter {
  write(data) {
    this.emit('data', data);
  }
}

const stream = new MyStream();

stream.on('data', (data) => {
  console.log(`接收的数据:"${data}"`);
});
stream.write('使用 ES6');

 

8.util.inspect(object[, options])

 

9.util.inspect(object[, showHidden[, depth[, colors]]])

 

10.util.isDeepStrictEqual(val1, val2)

val1 <任何>
val2 <任何>
返回:<boolean>
true如果val1和之间存在严格的严格相等,则返回val2。否则,返回false。

11.util.promisify(original)

1.

const stat = util.promisify(fs.stat);
stat('.').then((value) => {
    // console.log(value)
});
console.log(stat('.'))
const setImmediatePromise = util.promisify(setImmediate);

setImmediatePromise(123).then((value) => {
    // console.log(value)

    });

输出;

Promise { <pending> }

 

 2.

const util = require('util');
const fs = require('fs');


doSomething =fs.stat;
doSomething1 = doSomething[util.promisify.custom] = (foo) => {
    // console.log(foo)
    return 1
};
console.log(doSomething[util.promisify.custom])
const promisified123 = util.promisify(doSomething);


console.log(promisified123,promisified123('123'),doSomething1('123'));
console.log(Promise.resolve(1))
console.log(new Promise((resolve, reject) => resolve(1)));

 输出:

[Function]
[Function] 1 1
Promise { 1 }
Promise { 1 }

 这样他返回的就是一个普通的函数 

3.模仿promise

const util = require('util');
const fs = require('fs');


doSomething =fs.stat;
doSomething1 = doSomething[util.promisify.custom] = (foo) => {

    return new Promise((resolve, reject) => {
       resolve(1)
    });
};

const promisified123 = util.promisify(doSomething);


console.log(promisified123,
    promisified123('123').then(value => console.log(value),error=>console.log(error)),
    doSomething1('123'));

输出:

[Function] Promise { <pending> } Promise { 1 }
1

 

function doSomething(foo) {
    function callback(resolve,reject){
        resolve(1)
    }
}
doSomething1 = doSomething[util.promisify.custom] = (foo) => {

    return new Promise((resolve, reject) => {
        doSomething(foo, resolve, reject);
    });
};

const promisified123 = util.promisify(doSomething);


console.log(
    promisified123('./a.txt').
    then(value => console.log(value),error=>console.log(error)));

暂时写不下去。总之如果普通的写,写到第二步就好了。

 

 

 

const util = require('util');
function fn() {
    return Promise.resolve(66);
}
const callbackFunction = util.callbackify(fn);

callbackFunction((err, ret) => {
    // 当 Promise 被以 `null` 拒绝时,它被包装为 Error 并且原始值存储在 `reason` 中。
    console.log(err)
    console.log(ret)
    console.log(err && err.hasOwnProperty('reason') && err.reason === null)  // true
});
null
66
null

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值