我想使用[email protected]和管道在NodeJS 0.10.x中流式传输大文件。目前我是
这样做(在CoffeeScript中):

app.get   '/', ( request, response ) ->
  input = P.create_readstream route
  input
    .pipe P.$split()
    .pipe P.$trim()
    .pipe P.$skip_empty()
    .pipe P.$skip_comments()
    .pipe P.$parse_csv headers: no, delimiter: '\t'
    .pipe response


Ppipedreams。)

我想拥有的是

    .pipe count_bytes       # ???
    .pipe response
    .pipe report_progress response


因此,当我查看终端中运行的服务器时,会得到一些指示,表明已经有多少字节
被客户接受。现在,很烦人的是,看到客户加载了多个年龄而又没有
任何表明是在一分钟内还是明天进行传输的指示。

有没有中间件可以做到这一点?我找不到任何东西。

哦,在回复完成时我必须打个电话吗?它看起来确实正在自动地工作。

最佳答案

对于第二个问题,您不必关闭任何内容。 pipe函数可以为您处理所有事务,甚至可以限制流(如果源流由于下载速度较慢而导致数据量超出客户端无法处理的数据,它将暂停源流,直到客户端可以再次使用源而不是使用)通过完全阅读源代码来使用一堆内存服务器端)。

对于第一个问题,要在流上包含一些统计服务器端,可以使用的是Transform流,例如:

var Transform = require('stream').Transform;
var util = require('util').inherits;

function StatsStream(ip, options) {
    Transform.call(this, options);
    this.ip = ip;
}

inherits(StatsStream, Transform);

StatsStream.prototype._transform = function(chunk, encoding, callback) {
    // here some bytes have been read from the source and are
    // ready to go to the destination, do your logging here
    console.log('flowing ', chunk.length, 'bytes to', this.ip);

    // then tell the tranform stream that the bytes it should
    // send to the destination is the same chunk you received...
    // (and that no error occured)
    callback(null, chunk);
};


然后,在您的请求处理程序中,您可以通过管道进行传递(抱歉javascript):

input.pipe(new StatsStream(req.ip)).pipe(response)


我做到了这一点,所以要当心:)

10-06 09:38