gpt4 book ai didi

javascript - 如何在 Deno 中下载大文件?

转载 作者:行者123 更新时间:2023-12-01 15:37:11 24 4
gpt4 key购买 nike

我正在尝试下载一个 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在每个 block 上。

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

您也可以使用 fromStreamReader来自 std/io ( >= std@v0.60.0 ) 转换为 res.bodyReader可用于 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();

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

关于javascript - 如何在 Deno 中下载大文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61945050/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com