【问题标题】:watching streaming HTTP response progress in NodeJS, express在 NodeJS 中观看流式 HTTP 响应的进度,表达
【发布时间】:2014-10-14 03:49:15
【问题描述】:

我想使用 express@4.8.5 和管道在 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

所以当我查看终端中运行的服务器时,我得到了一些关于已经有多少字节的指示 被客户接受。现在,看到客户端加载很长时间而没有 任何指示传输是在一分钟内还是明天完成。

是否有任何中间件可以做到这一点?我找不到。

哦,我必须在响应完成时调用任何东西吗?看起来它现在正在自动运行。

【问题讨论】:

    标签: node.js http stream coffeescript response


    【解决方案1】:

    对于第二个问题,您不必关闭任何内容。 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)
    

    我是在头顶上做的,所以要小心:)

    【讨论】:

    • 我知道我可以这样做,而且我以前也这样做过,计算管道中的字节数。我想做并且怀疑不可能做的是测量客户端 HTTP 回复的进度,或者至少实际通过网络抽取了多少字节。
    • 那么您必须知道管道是如何通过管道传输的:如果对目标缓冲区的写入未刷新到内核(当客户端无法下载为源可以提供的速度快)。如果客户端不能像读取的一样快地从源中下载,则不会完全读取源:服务器会在所有客户端连接时消耗太多内存。相反,它是流式传输的。这就是管道方法的作用。您说客户端连接到您的管道几分钟,所以我想听管道将是您想要的数据的一个很好的近似值。
    猜你喜欢
    • 2012-04-02
    • 2020-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-25
    • 2016-01-29
    • 1970-01-01
    相关资源
    最近更新 更多