简单的流读写实现
var Readable = require('stream').Readable;
var Writable = require('stream').Writable;
var rs = Readable();
var ws = Writable();
var c = 97 - 1;
rs._read = function () {
if (c >= 'z'.charCodeAt(0)) return rs.push(null);
setTimeout(function () {
rs.push(String.fromCharCode(++c));
}, 1000);
};
rs.pipe(ws);
ws._write = function (chunk, enc, next) {
process.stdout.write(chunk);
next();
};
process.on('exit', function () {
console.error('\n_read() called ' + (c - 97) + ' times');
});
process.stdout.on('error', process.exit);
const Transform = require('stream').Transform;
const util = require('util');
const fs= require('fs');
function MyTransform(filter) {
if (!(this instanceof MyTransform))
return new MyTransform(null);
Transform.call(this, null);
this.temp = new Buffer(6);
this.filter = filter;
}
util.inherits(MyTransform, Transform);
MyTransform.prototype._transform = function (data, encoding, callback) {
let len=0;
let blen=0;
let c=null;
for (let b of data) {
if(len == 0){
if(b<128){
len=1;
}else if(b<224){
len=2;
}else if(b<240){
len=3;
}else if(b<248){
len=4;
}else if(b<252){
len=5;
}else if(b<254){
len=6;
}else{
continue;
}
blen=len;
}else{
if( b<128 || 191<b){
len=0;
blen=0;
continue;
}
}
len--;
this.temp[blen-len-1]=b;
if(len < 1){
c = this.temp.slice(0, blen);
if(c.toString()!=this.filter){
this.push(c);
}
}
}
callback();
};
const is = fs.createReadStream('a.txt');
is.pipe(new MyTransform('a')).pipe(process.stdout);