]> git.ardis.lu - csvio/commitdiff
Block `cancel()` until `start()` is finished
authorArdis Lu <ardisglu@gmail.com>
Mon, 28 Apr 2025 06:07:57 +0000 (23:07 -0700)
committerArdis Lu <ardisglu@gmail.com>
Mon, 28 Apr 2025 06:07:57 +0000 (23:07 -0700)
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.

src/core.js

index 333db9a3568b0e522000346dffa284b16acd1109..5ffcec43372a959bb8ff40d4a00680d1068e1493 100644 (file)
@@ -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();
     }
   });
This page took 0.049883 seconds and 4 git commands to generate.