How do I read a binary chunked response using the Fetch API. I'm using the following code which works insofar it reads the chunked response from the server. However, the data seems to be encoded/decoded somehow causing the getFloat32
to sometimes fail. I've tried to read the response with curl, and that works fine, leading me to believe I need to do something to make fetch api treat chunks as binary. The content-type of the response is properly set to "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);
Use the following express server to reproduce it. Note, any client side js code that can handle the below server is fine.
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!'));
Using the above node server -13614102509256704 will be logged to console, but it should just be ~16.48. How can I retrieve the original binary float written?