|
import { createReadStream } from "node:fs"; |
|
import { open, stat } from "node:fs/promises"; |
|
import { Readable } from "node:stream"; |
|
import type { FileHandle } from "node:fs/promises"; |
|
import { fileURLToPath } from "node:url"; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export class FileBlob extends Blob { |
|
|
|
|
|
|
|
|
|
|
|
static async create(path: string | URL): Promise<FileBlob> { |
|
path = path instanceof URL ? fileURLToPath(path) : path; |
|
|
|
const { size } = await stat(path); |
|
|
|
const fileBlob = new FileBlob(path, 0, size); |
|
|
|
return fileBlob; |
|
} |
|
|
|
private path: string; |
|
private start: number; |
|
private end: number; |
|
|
|
private constructor(path: string, start: number, end: number) { |
|
super(); |
|
|
|
this.path = path; |
|
this.start = start; |
|
this.end = end; |
|
} |
|
|
|
|
|
|
|
|
|
override get size(): number { |
|
return this.end - this.start; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
override slice(start = 0, end = this.size): FileBlob { |
|
if (start < 0 || end < 0) { |
|
new TypeError("Unsupported negative start/end on FileBlob.slice"); |
|
} |
|
|
|
const slice = new FileBlob(this.path, this.start + start, Math.min(this.start + end, this.end)); |
|
|
|
return slice; |
|
} |
|
|
|
|
|
|
|
|
|
override async arrayBuffer(): Promise<ArrayBuffer> { |
|
const slice = await this.execute((file) => file.read(Buffer.alloc(this.size), 0, this.size, this.start)); |
|
|
|
return slice.buffer; |
|
} |
|
|
|
|
|
|
|
|
|
override async text(): Promise<string> { |
|
const buffer = (await this.arrayBuffer()) as Buffer; |
|
|
|
return buffer.toString("utf8"); |
|
} |
|
|
|
|
|
|
|
|
|
override stream(): ReturnType<Blob["stream"]> { |
|
return Readable.toWeb(createReadStream(this.path, { start: this.start, end: this.end - 1 })) as ReturnType< |
|
Blob["stream"] |
|
>; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
private async execute<T>(action: (file: FileHandle) => Promise<T>) { |
|
const file = await open(this.path, "r"); |
|
|
|
try { |
|
return await action(file); |
|
} finally { |
|
await file.close(); |
|
} |
|
} |
|
} |
|
|