如何将Fetch响应转换为数组缓冲区?

9

使用像axios这样的库,我可以从HTTP请求中请求数据作为数组缓冲区:

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

        console.log(data)
        return data;
}

这将打印:

<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>

假设我没有指定数据以数组缓冲区的形式传输,或者我使用了简单的fetch请求:

const response = fetch(url)

我该如何将这个 response 转换为一个数组缓冲区?

我正在尝试实现以下操作:

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

console.log(buffer)

这段代码会输出什么:

<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>
2个回答

11

FetchAPI 使用 Response 对象来表示请求的响应。为了处理响应体的处理,有几个可用的方法

您可能熟悉Response.json,因为JSON是解释响应主体最常见的方式之一,但还有Response.arrayBuffer:

async function get(url) {
    const response = await fetch(url);
    return response.arrayBuffer();
}

1
这是一种在原生JavaScript中实现相同效果的简洁方法。
const response = await fetch(url);
const buffer = await response.arrayBuffer();
const bytes = new Uint8Array(buffer);

console.log(bytes);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接