【发布时间】:2014-03-13 16:27:16
【问题描述】:
我试图通过编写一个小脚本来学习 Nodejs 中的流式传输。但是在执行完这个之后,最后一个流并没有推送所有数据。
var stream = require('stream');
var fs = require('fs');
var util = require('util');
function Newliner () {
stream.Transform.call(this);
}
util.inherits(Newliner, stream.Transform);
Newliner.prototype._transform = function(chunk, enc, done) {
var split = 0;
for( var i =0; i <chunk.length; i++){
if(chunk[i] == 10) {
this.push(chunk.slice(split,i));
split = i+1;
}
}
}
function Greper(options) {
stream.Transform.call(this);
this.regex = new RegExp(options);
}
util.inherits(Greper, stream.Transform);
Greper.prototype._transform = function(chunk, enc, done) {
this.push(chunk); //Even this is not working.
/*
var a = chunk.toString();
if(this.regex.test(a)){
this.push(chunk);
}
*/
}
var n = new Newliner();
var g = new Greper("line");
var f = fs.createReadStream('a.txt');
f.pipe(n).pipe(g).pipe(process.stdout);
输入文件a.txt是,
This is line one.
Another line.
Third line.
执行时只显示一行。这是什么原因?
$ node test.js
This is line one.
注意:当我将文件读取流直接传输到“g”时,它可以正常工作。
【问题讨论】: