-
Notifications
You must be signed in to change notification settings - Fork 0
/
node-compat.js
39 lines (36 loc) · 1.16 KB
/
node-compat.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import { open } from "node:fs/promises"
/**
* @export
* @param {string} filePath
* @param {number} [chunkSize=16777216] - Default: 16MiB
* @return {ReadableStream<Uint8Array>}
*/
export function openFileAsReadableStream(filePath, chunkSize = 16777216) {
/** @type {import("node:fs/promises").FileHandle} */
let fileHandle;
let position = 0;
return new ReadableStream({
type: "bytes",
async start() {
fileHandle = await open(filePath, "r");
},
async pull(controller) {
if (!controller.byobRequest) throw "No BYOB Request"
if (!controller.byobRequest.view) throw "No View in BYOB Request"
const view = controller.byobRequest.view;
const { bytesRead } = await fileHandle.read(new Uint8Array(view.buffer, view.byteOffset, view.byteLength), 0, view.byteLength, position);
if (bytesRead === 0) {
await fileHandle.close();
controller.close();
controller.byobRequest.respond(0);
} else {
position += bytesRead;
controller.byobRequest.respond(bytesRead);
}
},
async cancel() {
return await fileHandle.close();
},
autoAllocateChunkSize: chunkSize
});
}