簡體   English   中英

在NodeJS中觀看流式HTTP響應進度

[英]watching streaming HTTP response progress in NodeJS, express

我想使用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

P白日夢 。)

我想擁有的是

    .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)

我做到了這一點,所以要當心:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM