【问题标题】:Nodejs: Transport stream is not pumping data out completely?Nodejs:传输流没有完全抽出数据?
【发布时间】: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”时,它可以正常工作。

【问题讨论】:

    标签: node.js stream


    【解决方案1】:

    您需要在处理完块后调用_transform() 函数的回调。来自the documentation

    callback(函数)在处理完提供的块后调用此函数(可选地带有错误参数)。

    在调用回调之前,不会有更多数据被推送到流中。如果您不调用它,则该块将不会被视为已处理……这就是为什么您的程序在仅处理一行后停止的原因。

    只需添加:

    done();
    

    Newliner.prototype._transformGreper.prototype._transform 函数的末尾。

    【讨论】:

    • 在调用 done() 后它工作了。非常感谢保罗。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-21
    • 2020-02-28
    • 2021-05-28
    • 1970-01-01
    • 2017-12-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多