The util module is primarily designed to support the needs of Node.js' own internal APIs. However, many of the utilities are useful for application and module developers as well. It can be accessed using:

const util = require('util');

具体内容查看文档

这里说一说我自己的理解:
util模块一个重要用途就是对nodejs对象的继承

github

戳这里

实例1

var events = require('events');
var util = require('util');

//object constructor
var Person = function(name) {
    this.name = name;
}

util.inherits(Person, events.EventEmitter)

var AlexZ33 = new Person('AlexZ33');
var JingXin = new Person('JingXin');
var Tom = new Person('Tom');
var people = [AlexZ33, JingXin, Tom];

people.forEach(function(person) {
  person.on('speak', function(msg) {
      console.log(person.name + 'said:' + msg);
  });
});

AlexZ33.emit('speak', 'hey dudes');
JingXin.emit('speak', 'I am a lovely girl')

我希望所有新创建的person对象都继承EventEmitter,这样我们就能绑定自定义的事件到这些新创建的实例对象了(people

util.inherits(Person, events.EventEmitter)

图片描述

实例2

这是自定义的stream流读写代码

var stream = require('stream')
var util = require('util')


function ReadStream() {
    stream.Readable.call(this)
}

util.inherits(ReadStream, stream.Readable)

ReadStream.prototype._read = function() {
    this.push('I')
    this.push('Love')
    this.push('jxdxsw.com\n')
    this.push(null)


}

function WriteStream() {

    stream.Writable.call(this)
    this._cached = new Buffer('')

}

util.inherits(WriteStream,stream.Writable)

WriteStream.prototype._write = function(chunk,encode,callback) {

    console.log(chunk.toString());
    callback()
}



function TransformStream() {
    stream.Transform.call(this)
}

util.inherits(TransformStream,stream.Transform)

TransformStream.prototype._transform = function(chunk,encode,callback) {
    this.push(chunk)
    callback()

}

TransformStream.prototype._flush = function(callback) {

    this.push('Oh my God!')
    callback()
    
}

var rs = new ReadStream()
var ws = new WriteStream()
var ts = new TransformStream

rs.pipe(ts).pipe(ws)


 

同样的,我希望所有新创建的stream对象分别继承stream的stream.Readablestream.Writablestream.Transform,这样我们就能绑定自定义的stream方法到这些新创建的stream实例对象了
ps: 自定义stream方法用 _xxx表示


白鲸鱼
1k 声望110 粉丝

方寸湛蓝