如何在 Deno 中下载大文件?

How can I download big files in Deno?

我正在尝试下载一个 10GB 的文件,但只有 4GB 保存到磁盘,而且内存正在增长很多。

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)

您正在缓冲响应,这就是内存增长的原因。

您可以遍历 res.body,因为它目前是一个 ReadableStream,它实现 Symbol.asyncIterator 并在每个块上使用 Deno.writeAll

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

您还可以使用 std/io (>= std@v0.60.0) 中的 fromStreamReaderres.body 转换为可以在 [=21= 中使用的 Reader ]

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();

关于为什么它停在 4GB 我不确定,但这可能与 ArrayBuffer / UInt8Array 限制有关,因为 4GB 大约是 2³² 字节,这是 TypedArray, at least in most runtimes.