如何正确计算已处理的node.js流的字节数?

时间:2015-03-24 21:46:48

标签: node.js stream

我有一条小节,我通过网络发送并花了一些时间完全发送,所以我想显示它在飞行中的距离。我知道你可以听取数据'流的事件,但在较新版本的节点中,它还将流放入"流动模式"。我想确保我正确地做到这一点。

目前我有以下内容:

deploymentPackageStream.pause() // to prevent it from entering "flowing mode"
var bytesSent = 0
deploymentPackageStream.on('data', function(data) {
    bytesSent+=data.length
    process.stdout.write('\r                   ')
    process.stdout.write('\r'+(bytesSent/1000)+'kb sent')
})
deploymentPackageStream.resume()

// copy over the deployment package
execute(conn, 'cat > deploymentPackage.sh', deploymentPackageStream).wait()     

这给了我正确的bytesSent输出,但是得到的包似乎丢失了前面的一些数据。如果我把简历放在'在执行复制行(最后一行)后,它不会复制任何内容。如果我不恢复,它也不会复制任何东西。发生了什么以及如何在不中断流而不进入流动模式的情况下正确执行此操作(我想要背压)?

我应该提一下,我还在使用node v0.10.x

1 个答案:

答案 0 :(得分:0)

好吧,我做了一些基本上是直通的东西,但是当它进来时调用数据回调:

// creates a stream that can view all the data in a stream and passes the data through
// parameters:
    // stream - the stream to peek at
    // callback - called when there's data sent from the passed stream
var StreamPeeker = exports.StreamPeeker = function(stream, callback) {
    Readable.call(this)
    this.stream = stream

    stream.on('readable', function() {
        var data = stream.read()
        if(data !== null) {
            if(!this.push(data)) stream.pause()
            callback(data)
        }
    }.bind(this))

    stream.on('end', function() {
        this.push(null)
    }.bind(this))
}
util.inherits(StreamPeeker, Readable)
StreamPeeker.prototype._read = function() {
    this.stream.resume()
}

如果我理解了溪流,这应该适当地处理背压。

使用这个,我可以在回调中计算data.length,如下所示:

var peeker = new StreamPeeker(stream, function(data) {
   // use data.length
})
peeker.pipe(destination)