如何在 Deno 中将 arrayBuffer 转换为 Uint8Array?
How to convert an arrayBuffer to a Uint8Array, in Deno?
我正在使用提取 api 在 Deno 中下载图像。在 Response 对象上,我正在调用 arrayBuffer() 方法,以获取响应的最终数据:
const response = await fetch('https://www.example.com/someimage.jpg')
const data = await response.arrayBuffer();//This returns an arrayBuffer.
然后我想将这些数据写入文件,就像您在 Node 中所做的那样:
await Deno.writeFile('./someimage.jpg' ,data)
图像原来是空的。文档说 Deno.writeFile 需要一个 Uint8Array,但我不知道如何从 arrayBuffer 构造它,它是从获取响应中接收到的。
如何做到这一点?
您必须将 ArrayBuffer
传递给 Uint8Array
构造函数
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))
嗯...根据文档 (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array),您只需执行以下操作:
// const data = await response.arrayBuffer();
const data = new ArrayBuffer(2); // Mock
const convertedData = new Uint8Array(data);
console.log(convertedData);
我正在使用提取 api 在 Deno 中下载图像。在 Response 对象上,我正在调用 arrayBuffer() 方法,以获取响应的最终数据:
const response = await fetch('https://www.example.com/someimage.jpg')
const data = await response.arrayBuffer();//This returns an arrayBuffer.
然后我想将这些数据写入文件,就像您在 Node 中所做的那样:
await Deno.writeFile('./someimage.jpg' ,data)
图像原来是空的。文档说 Deno.writeFile 需要一个 Uint8Array,但我不知道如何从 arrayBuffer 构造它,它是从获取响应中接收到的。
如何做到这一点?
您必须将 ArrayBuffer
传递给 Uint8Array
构造函数
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))
嗯...根据文档 (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array),您只需执行以下操作:
// const data = await response.arrayBuffer();
const data = new ArrayBuffer(2); // Mock
const convertedData = new Uint8Array(data);
console.log(convertedData);