Created
April 16, 2025 13:13
-
-
Save rwv/a4faf6af816748be3ae6f43582619dab to your computer and use it in GitHub Desktop.
Tauri wrtie file from ReadableStream
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { writeFile, type WriteFileOptions } from '@tauri-apps/plugin-fs' | |
export async function writeFileFromStream( | |
path: string | URL, | |
stream: ReadableStream<Uint8Array>, | |
options?: WriteFileOptions & { chunkSize?: number } | |
) { | |
const chunkSize = options?.chunkSize ?? 1024 * 1024 // 1MB in bytes | |
const reader = stream.getReader() | |
let chunks: Uint8Array[] = [] | |
let bytesRead = 0 | |
// eslint-disable-next-line no-constant-condition | |
while (true) { | |
const { done, value } = await reader.read() | |
if (done) break | |
chunks.push(value) | |
bytesRead += value.length | |
if (bytesRead >= chunkSize) { | |
const chunk = new Uint8Array(bytesRead) | |
let offset = 0 | |
for (const chunkValue of chunks) { | |
chunk.set(chunkValue, offset) | |
offset += chunkValue.length | |
} | |
await writeFile(path, chunk, { | |
...options, | |
append: true | |
}) | |
chunks = [] | |
bytesRead = 0 | |
} | |
} | |
if (bytesRead > 0) { | |
const chunk = new Uint8Array(bytesRead) | |
let offset = 0 | |
for (const chunkValue of chunks) { | |
chunk.set(chunkValue, offset) | |
offset += chunkValue.length | |
} | |
await writeFile(path, chunk, { | |
...options, | |
append: true | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment