Reuse arrayBuffer for fetch response

233 views Asked by At

I use fetch API to perform HTTP requests. Because the HTTP response body is a binary, I use response.arrayBuffer() method to get the result as bytes. Anyway, this approach doesn't perform well when the application makes a lot of HTTP requests because every time response.arrayBuffer method is invoked, it returns a new instance of ArrayBuffer. I didn't find any solution to provide my own ArrayBuffer instance to the Response method to avoid a new allocation.

Is there any solution I can follow to let my application perform better?

1

There are 1 answers

0
didinko On

Unfortunatelly response.arrayBuffer() could be reused directly. A possible workaround would be to split the response into chunks and create multiple buffers from it using Buffer.concat:

const response = await fetch('url');
const chunks = [];
for await (const chunk of response.body) {
    chunks.push(Buffer.from(chunk));
}
await sharp(Buffer.concat(chunks)).toFile('name');
await sharp(Buffer.concat(chunks)).toFile('name1');