From da06f3d35424bb2bf52548c56a53f470b71e2894 Mon Sep 17 00:00:00 2001 From: tyoshino Date: Thu, 10 Mar 2016 10:02:23 +0900 Subject: [PATCH] Make makeReadableByteFileStream example able to handle non BYOB case --- index.bs | 36 ++++++++++++++++++++++++++---------- 1 file changed, 26 insertions(+), 10 deletions(-) diff --git a/index.bs b/index.bs index 74db737c8..c0e726a5b 100644 --- a/index.bs +++ b/index.bs @@ -3253,6 +3253,7 @@ size of 1024, it attempts to fill the developer-supplied buffer, allowing full c

   const fs = require("pr/fs"); // https://github.com/jden/pr
+  const CHUNK_SIZE = 1024;
 
   function makeReadableByteFileStream(filename) {
     let fd;
@@ -3268,16 +3269,31 @@ size of 1024, it attempts to fill the developer-supplied buffer, allowing full c
       },
 
       pull(controller) {
-        const v = controller.byobRequest.view;
-
-        return fs.read(fd, v, v.byteOffset, v.byteLength, position).then(bytesRead => {
-          if (bytesRead === 0) {
-            return fs.close(fd).then(() => controller.close());
-          } else {
-            position += bytesRead;
-            controller.byobRequest.respond(bytesRead);
-          }
-        });
+        const r = controller.byobRequest;
+
+        if (r) {
+          const v = r.view;
+
+          return fs.read(fd, v.buffer, v.byteOffset, v.byteLength, position).then(bytesRead => {
+            if (bytesRead === 0) {
+              return fs.close(fd).then(() => controller.close());
+            } else {
+              position += bytesRead;
+              controller.byobRequest.respond(bytesRead);
+            }
+          });
+        } else {
+          // The consumer is using the default reader.
+          const buffer = new ArrayBuffer(CHUNK_SIZE);
+          return fs.read(fd, buffer, 0, CHUNK_SIZE, position).then(bytesRead => {
+            if (bytesRead === 0) {
+              return fs.close(fd).then(() => controller.close());
+            } else {
+              position += bytesRead;
+              controller.enqueue(new Uint8Array(buffer, 0, bytesRead));
+            }
+          });
+        }
       },
 
       cancel() {