Line data Source code
1 : /**
2 : * Reads a file (optionally capped to its first `maxBytes`) into an ArrayBuffer.
3 : * Resolves `null` when the read errors, aborts, or yields no result, so callers
4 : * can guard with a single truthiness check before parsing. The underlying
5 : * `FileReader` error reason is intentionally not surfaced; callers treat any
6 : * failure as "no metadata" rather than distinguishing causes.
7 : * @param file - The file to read.
8 : * @param maxBytes - Optional cap; when set, only the first `maxBytes` are read.
9 : */
10 17 : export function readFileAsArrayBuffer(
11 : file: File,
12 : maxBytes?: number
13 : ): Promise<ArrayBuffer | null> {
14 17 : return new Promise<ArrayBuffer | null>((resolve) => {
15 17 : const reader = new FileReader()
16 17 : reader.onload = () => {
17 17 : resolve(reader.result instanceof ArrayBuffer ? reader.result : null)
18 : }
19 17 : reader.onerror = () => resolve(null)
20 17 : reader.onabort = () => resolve(null)
21 17 : const blob = maxBytes === undefined ? file : file.slice(0, maxBytes)
22 17 : reader.readAsArrayBuffer(blob)
23 : })
24 : }
|