How to convert an arrayBuffer to a Uint8Array, in Deno?
Asked Answered
T

2

10

I'm using the fetch api to download an image in Deno. On the Response object, i'm calling the arrayBuffer() method, to get the final data of the response:

const response = await fetch('https://www.example.com/someimage.jpg')
const data = await response.arrayBuffer();//This returns an arrayBuffer.

Then i want to write this data into a file, just like you would do in Node:

await Deno.writeFile('./someimage.jpg' ,data)

The image turns out empty. The docs say Deno.writeFile expects a Uint8Array, but i have no clue how to construct this from the arrayBuffer, that is received from the fetch response.

How can this be done?

Trioxide answered 6/7, 2020 at 18:51 Comment(0)
O
20

You have to pass the ArrayBuffer to the Uint8Array constructor

You cannot directly manipulate the contents of an ArrayBuffer; instead, you create one of the typed array objects or a DataView object which represents the buffer in a specific format, and use that to read and write the contents of the buffer.

new Uint8Array(arrayBuffer);

const response = await fetch('https://www.example.com/someimage.jpg')
const data = await response.arrayBuffer();//This returns an arrayBuffer.
await Deno.writeFile('./someimage.jpg' , new Uint8Array(data))
Oarsman answered 6/7, 2020 at 19:1 Comment(3)
Yes i actually just saw this on another post, and realized it has nothing to do with Deno, just normal JS :DTrioxide
Exactly, that's just plain JS :).Oarsman
In case you want to stream to the file, instead of buffering, check my answer over here: #61945550Oarsman
T
2

Hmm... according to the docs (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) you simply do the following:

// const data = await response.arrayBuffer();
const data = new ArrayBuffer(2); // Mock
const convertedData = new Uint8Array(data);

console.log(convertedData);
Trahan answered 6/7, 2020 at 19:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.