48 lines
1.6 KiB
TypeScript
48 lines
1.6 KiB
TypeScript
import * as fs from "node:fs"
|
|
import * as asyncfs from "node:fs/promises"
|
|
import * as Path from "node:path"
|
|
import mime from "mime"
|
|
import type { Blob as WebBlob, File as WebFile, ReadableStream } from "@sugoidogo/importable-types-web";
|
|
import { Blob } from "node:buffer";
|
|
import { Readable } from "node:stream";
|
|
|
|
export default class NonBufferedFile implements WebFile {
|
|
webkitRelativePath: string;
|
|
#path: string
|
|
constructor(path: string, webkitRelativePath:string) {
|
|
this.#path = Path.resolve(path)
|
|
this.webkitRelativePath=webkitRelativePath
|
|
}
|
|
get lastModified() {
|
|
return fs.statSync(this.#path).mtimeMs
|
|
}
|
|
get size() {
|
|
return fs.statSync(this.#path).size
|
|
}
|
|
get type() {
|
|
return mime.getType(this.#path)
|
|
}
|
|
get name() {
|
|
return Path.basename(this.#path)
|
|
}
|
|
async bytes(): Promise<Uint8Array<ArrayBuffer>> {
|
|
return asyncfs.readFile(this.#path)
|
|
}
|
|
async arrayBuffer(): Promise<ArrayBuffer> {
|
|
const bytes = await asyncfs.readFile(this.#path)
|
|
return bytes.buffer
|
|
}
|
|
async text(): Promise<string> {
|
|
return asyncfs.readFile(this.#path,"utf8")
|
|
}
|
|
slice(start?: number, end?: number, contentType?: string): WebBlob {
|
|
const fd = fs.openSync(this.#path, fs.constants.O_RDONLY)
|
|
const buffer=new Uint8Array()
|
|
fs.readSync(fd, buffer, { "position": start, "length": end - start })
|
|
fs.closeSync(fd)
|
|
return new Blob([buffer],{"type":contentType||this.type}) as any
|
|
}
|
|
stream(): ReadableStream<Uint8Array<ArrayBuffer>> {
|
|
return Readable.toWeb(fs.createReadStream(this.#path)) as any
|
|
}
|
|
} |