javascript - 使用 Fetch API 读取分块二进制响应

标签 javascript fetch-api chunked

如何使用 Fetch API 读取二进制分块响应。我正在使用以下代码,它可以从服务器读取分块响应。但是,数据似乎以某种方式被编码/解码,导致 getFloat32 有时会失败。我尝试使用 curl 读取响应,效果很好,这让我相信我需要做一些事情来让 fetch api 将 block 视为二进制文件。响应的内容类型正确设置为“application/octet-stream”。

const consume = responseReader => {
    return responseReader.read().then(result => {
        if (result.done) { return; }
        const dv = new DataView(result.value.buffer, 0, result.value.buffer.length);
        dv.getFloat32(i, true);  // <-- sometimes this is garbled up
        return consume(responseReader);
    });
}

fetch('/binary').then(response => {
    return consume(response.body.getReader());
})
.catch(console.error);

使用下面的express server重现。请注意,任何可以处理以下服务器的客户端 js 代码都可以。

const express = require('express');
const app = express();

app.get('/binary', function (req, res) {
  res.header("Content-Type", "application/octet-stream");
  res.header('Content-Transfer-Encoding', 'binary');
  const repro = new Uint32Array([0x417055b8, 0x4177d16f, 0x4179e9da, 0x418660e1, 0x41770476, 0x4183e05e]);
  setInterval(function () {
    res.write(Buffer.from(repro.buffer), 'binary');
  }, 2000);
});

app.listen(3000, () => console.log('Listening on port 3000!'));

使用上面的节点服务器 -13614102509256704 将被记录到控制台,但它应该只是 ~16.48。如何检索写入的原始二进制 float ?

最佳答案

正如您指出的,您的问题是

The getFloat32 function takes a byte offset, clearly documented

但是您的工作还有另一面。所以我会在这里添加它

默认情况下,FFChrome 都不支持 Fetch Streams,我更新了我的代码以在两端都使用流。

const express = require('express');
const app = express();

app.get('/', function (req, res) {
    res.send(`
    <html>
    <body>
        <h1>Chrome reader</h1>
        <script>
            function dothis() {
var chunkedUrl = '/binary';
fetch(chunkedUrl)
  .then(processChunkedResponse)
  .then(onChunkedResponseComplete)
  .catch(onChunkedResponseError)
  ;

function onChunkedResponseComplete(result) {
  console.log('all done!', result)
}

function onChunkedResponseError(err) {
  console.error(err)
}

function processChunkedResponse(response) {
  var text = '';
  var reader = response.body.getReader()

  return readChunk();

  function readChunk() {
    return reader.read().then(appendChunks);
  }

  function appendChunks(result) {
      if (!result.done){
        var chunk = new Uint32Array(result.value.buffer);      
        console.log('got chunk of', chunk.length, 'bytes')
        console.log(chunk)
      }

    if (result.done) {
      console.log('returning')
      return "done";
    } else {
      console.log('recursing')
      return readChunk();
    }
  }
}            }
        </script>
    </body>
</html>

    `);
});

app.get('/firefox', function (req, res) {
    res.send(`
<html>
<head>
    <script src="./fetch-readablestream.js"></script>
    <script src="./polyfill.js"></script>
</head>
<body>
    <h1>Firefox reader</h1>
    <script>
    function readAllChunks(readableStream) {
                  const reader = readableStream.getReader();
                  const chunks = [];

                  function pump() {
                    return reader.read().then(({ value, done }) => {
                      if (done) {
                          console.log("its completed")
                        return chunks;
                      }
                      try{
                          console.log(new Int32Array(value.buffer))
                      }
                      catch (err) {
                          console.log("error occured - " + err)
                      }
                      return pump();
                    });
                  }

                  return pump();
            }

        function dothis() {


    fetchStream('/binary', {stream: true})
    .then(response => readAllChunks(response.body))
    .then(chunks => console.dir(chunks))
    .catch(err => console.log(err));
}            
        </script>
    </body>
</html>

    `);


});

app.get('/binary', function (req, res) {
    res.header("Content-Type", "application/octet-stream");
    res.header('Content-Transfer-Encoding', 'binary');
    const repro = new Uint32Array([0x417055b8, 0x4177d16f, 0x4179e9da, 0x418660e1, 0x41770476, 0x4183e05e]);
    i = 0;
    setTimeout(function abc() {
        res.write(Buffer.from(repro.buffer), 'binary');
        i++;
        if (i < 100) {
            setTimeout(abc, 100);
        } else {
            res.end();
        }
    }, 100)


    // I'm actually using spawn('command').pipe(res) here... So chunked response is required.
});
app.use(express.static('./node_modules/fetch-readablestream/dist/'))
app.use(express.static('./node_modules/web-streams-polyfill/dist/'))
app.listen(3000, () => console.log('Listening on port 3000!'));

现在它可以在 FF 上运行

FF

以及 Chrome

Chrome

你需要使用

https://www.npmjs.com/package/fetch-readablestream

我还在 FF 中为 ReadableStream 使用了 polyfill。

https://www.npmjs.com/package/web-streams-polyfill

但是您可以通过更改 FF 配置文件首选项来启用对相同内容的原生支持

FF config

添加到此处以便将来可能对您或其他人有所帮助

关于javascript - 使用 Fetch API 读取分块二进制响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49828310/

相关文章:

javascript - Bing 图像存档 Ajax 错误

javascript - 访问返回的 promise 的结果

http - 如果未发送 HTTP header ,如何确定分块编码的内容数据长度

python - urllib2 python (传输编码 : chunked)

http - Tomcat 有时会返回没有 HTTP header 的响应

javascript - 将 RGB 颜色值转换为 0.75 alpha 的 RGBA

javascript - 从子组件导航时刷新父组件

javascript - 如何在现有对象上调用 EventEmitter

javascript - 用 Fetch API 替换 $http

javascript - react .js : Parent state values not passing into child properties + Fetch API data cannot be accessed