Node学习记录: util模块

本文介绍了Node.js中util模块的功能及使用方法,重点讲解如何利用util.inherits实现对象继承,通过两个实例展示了如何为自定义对象和stream流对象添加自定义事件及方法。

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表示

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值