Is there a way to properly handle binary chunked responses when using the Fetch API? I have implemented the code below which successfully reads the chunked response from the server. However, I am encountering issues with the data being encoded/decoded in a way that sometimes causes the getFloat32
function to fail. When testing the response with curl, everything seems to work fine, suggesting that I may need to adjust something in the fetch api to treat the chunks as binary. The content-type of the response is correctly 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); // <-- experiencing garbled results at times
return consume(responseReader);
});
}
fetch('/binary').then(response => {
return consume(response.body.getReader());
})
.catch(console.error);
To test and reproduce the issue, use the following express server. Any client-side JS code that can interact with this server should suffice.
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!'));
When using the provided node server, you may notice that -13614102509256704 gets logged to the console instead of the expected value of ~16.48. How can one retrieve the original binary float value that was written?