From: Ardis Lu Date: Mon, 28 Apr 2025 06:07:57 +0000 (-0700) Subject: Block `cancel()` until `start()` is finished X-Git-Tag: v0.1.0~27 X-Git-Url: https://git.ardis.lu/?a=commitdiff_plain;h=af7aabf0ade3b22b477e1419ad0b661f50d31cb2;p=csvio Block `cancel()` until `start()` is finished If `cancel()` is called immediately after the stream is instantiated, it is possible that `start()` is not yet finished setting up the file handle before the `cancel()` logic is executed. --- diff --git a/src/core.js b/src/core.js index 333db9a..5ffcec4 100644 --- a/src/core.js +++ b/src/core.js @@ -36,11 +36,16 @@ export function createFileStream(path) { let handle; let position = 0; + // Can replace with Promise.withResolvers after Node.js v20 is no longer LTS + let resolveReady; + const ready = new Promise(r => { resolveReady = r }); + return new ReadableStream({ type: 'bytes', autoAllocateChunkSize: 1024, async start() { handle = await open(path, "r"); + resolveReady(); }, async pull(controller) { const v = controller.byobRequest.view; @@ -55,7 +60,8 @@ export function createFileStream(path) { controller.byobRequest.respond(bytesRead); } }, - cancel() { + async cancel() { + await ready; // If cancel() is called immediately after stream instantiation, start() may not have finished yet. return handle.close(); } });