简体   繁体   English

读取固定大小时,HTTP请求流无法激发可读性

[英]HTTP request stream not firing readable when reading fixed sizes

I am trying to work with the new Streams API in Node.js, but having troubles when specifying a fixed read buffer size. 我正在尝试使用Node.js中的新Streams API,但是在指定固定的读取缓冲区大小时遇到​​了麻烦。

var http = require('http');
var req = http.get('http://143.226.75.100/waug_mp3_128k', function (res) {
    res.on('readable', function () {
        var receiveBuffer = res.read(1024);
        console.log(receiveBuffer.length);
    });
});

This code will receive a few buffers and then exit. 此代码将接收一些缓冲区,然后退出。 However, if I add this line after the console.log() line: 但是,如果我在console.log()行之后添加此行:

res.read(0);

... all is well again. ...一切都恢复了。 My program continues to stream as predicted. 我的程序继续按预期播放。

Why is this happening? 为什么会这样呢? How can I fix it? 我该如何解决?

It's explained here . 在这里解释。

As far as I understand it, by reading only 1024 bytes with each readable event, Node is left to assume that you're not interested in the rest of the data that's in the stream buffers, and discards it. 据我了解,通过每个readable事件仅读取1024个字节,Node会假定您对流缓冲区中的其余数据不感兴趣,并丢弃它。 Issuing the read(0) (in the same event loop iteration) 'resets' this behaviour. 发出read(0) (在同一事件循环迭代中)“重置”此行为。 I'm not sure why the process exits after reading a couple of 1024-byte buffers though; 我不确定为什么在读取了几个1024字节的缓冲区后进程会退出; I can recreate it, but I don't understand it yet :) 我可以重新创建它,但是我还不明白:)

If you don't have a specific reason to use the 1024-byte reads, just read the entire buffer for each event: 如果没有特定的原因使用1024字节读取,则只需读取每个事件的整个缓冲区即可:

var receiveBuffer = res.read();

Or instead of using non-flowing mode, use flowing mode by using the data/end events instead: 或者代替使用非流模式,而通过使用data/end事件来使用流模式:

var http = require('http');
var req = http.get('http://143.226.75.100/waug_mp3_128k', function (res) {
  var chunks = [];
  res.on('data', function(chunk) {
    chunks.push(chunk);
    console.log('chunk:', chunk.length);
  });
  res.on('end', function() {
    var result = Buffer.concat(chunks);
    console.log('final result:', result.length);
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM