| Operate on written data, then read the result | Transform | _transform, _flush |
Readable流实现
如上所示,我们只要继承Readable类并实现_read接口即可,,如下所示:
const Readable = require('stream').Readable;
const util = require('util');
const alphabetArr = 'abcdefghijklmnopqrstuvwxyz'.split();
/*function AbReadable(){
if(!this instanceof AbReadable){
return new AbReadable();
}
Readable.call(this);
}
util.inherits(AbReadable,Readable);
AbReadable.prototype._read = function(){
if(!alphabetArr.length){
this.push(null);
}else{
this.push(alphabetArr.shift());
}
};const abReadable = new AbReadable();
abReadable.pipe(process.stdout);*/
/*class AbReadable extends Readable{
constructor(){
super();
}
_read(){
if(!alphabetArr.length){
this.push(null);
}else{
this.push(alphabetArr.shift());
}
}
}
const abReadable = new AbReadable();
abReadable.pipe(process.stdout);*/
/*const abReadable = new Readable({
read(){
if(!alphabetArr.length){
this.push(null);
}else{
this.push(alphabetArr.shift());
}
}
});
abReadable.pipe(process.stdout);*/
const abReadable = Readable();
abReadable._read = function(){
if (!alphabetArr.length) {
this.push(null);
} else {
this.push(alphabetArr.shift());
}
}
abReadable.pipe(process.stdout);
以上代码使用了四种方法创建一个Readable可读流,必须实现
_read()方法,以及用到了
readable.push()方法,该方法的作用是将指定的数据添加到读取队列。Writable流实现
我们只要继承Writable类并实现_write或_writev接口,如下所示(只使用两种方法):
/*class MyWritable extends Writable{
constructor(){
super();
}
_write(chunk,encoding,callback){
process.stdout.write(chunk);
callback();
}
}
const myWritable = new MyWritable();*/
const myWritable = new Writable({
write(chunk,encoding,callback){
process.stdout.write(chunk);
callback();
}
});
myWritable.on('finish',()=>{
process.stdout.write('done');
})
myWritable.write('a');
myWritable.write('b');
myWritable.write('c');
myWritable.end();Duplex流实现
实现Duplex流,需要继承Duplex类,并实现_read和_write接口,如下所示:
class MyDuplex extends Duplex{
constructor(){
super();









