当前位置: 首页 > 后端技术 > Node.js

Node学习记录:util模块

时间:2023-04-04 00:48:05 Node.js

util模块主要用于支持Node.js自己的内部API的需求。但是,许多实用程序对应用程序和模块开发人员也很有用。可以使用以下方式访问它:constutil=require('util');具体内容查看文档,这里说说自己的理解:util模块的一个重要用途就是继承nodejs对象github戳这里例1varevents=require('events');varutil=require('util');//对象构造函数varPerson=function(name){this.name=name;}util.inherits(Person,events.EventEmitter)varAlexZ33=newPerson('AlexZ33');varJingXin=newPerson('JingXin');varTom=newPerson('Tom');varpeople=[AlexZ33,JingXin,Tom];people.forEach(function(person){person.on('speak',function(msg){console.log(person.name+'said:'+msg);});});AlexZ33.emit('speak','heydudes');JingXin.emit('speak','我是个可爱的女孩')我要所有新创建的所有person对象都继承了EventEmitter,这样我们就可以给这些新创建的实例对象(people)绑定自定义事件util.inherits(Person,events.EventEmitter)例2这是自定义流读写代码varstream=require('溪流')varutil=require('util')functionReadStream(){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)}functionWriteStream(){stream.Writable.call(this)this._cached=newBuffer('')}util.inherits(WriteStream,stream.Writable)WriteStream.prototype._write=function(chunk,encode,callback){console.log(chunk.toString());callback()}functionTransformStream(){stream.Transform.call(this)}util.inherits(TransformStream,stream.Transform)TransformStream.prototype._transform=function(chunk,encode,callback){this.push(chunk)回调()}TransformStream.prototype._flush=function(callback){this.push('天哪!')callback()}varrs=newReadStream()varws=newWriteStream()varts=newTransformStreamrs.pipe(ts).pipe(ws)同样的,我希望所有新创建的stream对象分别继承stream的stream.Readable、stream.Writable,stream.Transform,这样我们就可以把自定义的流方法绑定到这些新创建的流实例对象上ps:自定义流方法用_xxx表示