How can I download big files in Deno?

痞子三分冷 提交于 2020-07-08 12:48:57

问题


I'm trying to download a 10GB file, but only 4GB get saved to disk, and memory is growing a lot.

const res = await fetch('https://speed.hetzner.de/10GB.bin');
const file = await Deno.open('./10gb.bin', { create: true, write: true })

const ab = new Uint8Array(await res.arrayBuffer())
await Deno.writeAll(file, ab)

回答1:


You're buffering the response, that's why the memory is growing.

You can iterate through res.body since it's currently a ReadableStream which implements Symbol.asyncIterator and use Deno.writeAll on each chunk.

for await(const chunk of res.body) {
    await Deno.writeAll(file, chunk);
}
file.close();

You can also use fromStreamReader from std/io (>= std@v0.60.0) to convert res.body to a Reader that can be used in Deno.copy

import { fromStreamReader } from "https://deno.land/std@v0.60.0/io/streams.ts";
const res = await fetch('https://speed.hetzner.de/10GB.bin');
const file = await Deno.open('./10gb.bin', { create: true, write: true })

const reader = fromStreamReader(res.body!.getReader());
await Deno.copy(reader, file);
file.close();

Regarding why it stops at 4GB I'm not sure, but it may have to do with ArrayBuffer / UInt8Array limits, since 4GB is around 2³² bytes, which is the limit of TypedArray, at least in most runtimes.



来源:https://stackoverflow.com/questions/61945050/how-can-i-download-big-files-in-deno

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!