How to convert fetch response to array buffer?
Asked Answered
G

2

12

Using a library like axios I can request data from a http request as an array buffer:

async function get(url) {
        const options =  { 
            method: 'GET',
            url: url,
            responseType: "arraybuffer"
        };
        const { data } = await axios(options);

        console.log(data)
        return data;
}

which prints:

<Buffer 50 4b 03 04 14 00 00 00 08 00 3c ef bf bd ef bf bd 52 ef bf bd ef bf bd 3a ef bf bd 46 01 00 00 6f 03 00 00 14 00 00 00 45 43 5f 72 61 77 2f 76 61 72 ... 1740004 more bytes>

Say I did't specify for data to come in as an array buffer or I used a simple fetch request:

const response = fetch(url)

How can I convert this response to an array buffer?

I am trying to do this:

const response = await this.get(test)
const buffer = Buffer.from(response)

console.log(buffer)

Which is printing this:

<Buffer 50 4b 03 04 14 00 00 00 08 00 3c ef bf bd ef bf bd 52 ef bf bd ef bf bd 3a ef bf bd 46 01 00 00 6f 03 00 00 14 00 00 00 45 43 5f 72 61 77 2f 76 61 72 ... 1740004 more bytes>
Gerhart answered 19/4, 2021 at 21:8 Comment(0)
E
16

The FetchAPI uses Response objects to represent the response to a request. To handle processing of the response body, there are several available methods.

You may be familiar with Response.json as JSON is one of the most common ways to interpret the response Body, but there is also Response.arrayBuffer:

async function get(url) {
    const response = await fetch(url);
    return response.arrayBuffer();
}
Ecumenicalism answered 19/4, 2021 at 22:3 Comment(0)
O
6

Here is a clean way to achieve the same in vanilla js:

const response = await fetch(url);
const buffer = await response.arrayBuffer();
const bytes = new Uint8Array(buffer);

console.log(bytes);
Orontes answered 30/10, 2023 at 12:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.