From e4edd1dcb48635c226832a1900d871d6c6906755 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jimmy=20W=C3=A4rting?= Date: Sat, 20 Apr 2019 09:50:14 +0200 Subject: [PATCH] Support new reading methods --- index.js | 104 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 104 insertions(+) diff --git a/index.js b/index.js index 53eaf0b..bd9d44c 100644 --- a/index.js +++ b/index.js @@ -84,6 +84,110 @@ function BlobConstructor(ary, options) { }; if (global.Blob) { + var stream; + + function promisify(obj) { + return new Promise(function(resolve, reject) { + obj.onload = + obj.onerror = function(evt) { + obj.onload = + obj.onerror = null; + + evt.type === 'load' + ? resolve(obj.result || obj) + : reject(new Error('Failed to read the blob/file')); + } + }) + } + + + try { + new ReadableStream({ type: 'bytes' }); + stream = function strea() { + var position = 0; + var blob = this; + + return new ReadableStream({ + type: 'bytes', + autoAllocateChunkSize: 524288, + + pull: function (controller) { + var v = controller.byobRequest.view; + var chunk = blob.slice(position, position + v.byteLength); + return chunk.arrayBuffer() + .then(function (buffer) { + var uint8array = new Uint8Array(buffer); + var bytesRead = uint8array.byteLength; + + position += bytesRead; + v.set(uint8array); + controller.byobRequest.respond(bytesRead); + + if (position >= blob.size) { + controller.close(); + } + }); + } + }); + } + } catch (e) { + try { + new ReadableStream({}); + stream = function stream (blob){ + var position = 0; + var blob = this; + + return new ReadableStream({ + pull: function (controller) { + var chunk = blob.slice(position, position + 524288); + + return chunk.arrayBuffer().then(function (buffer) { + position += buffer.byteLength; + var uint8array = new Uint8Array(buffer); + controller.enqueue(uint8array); + + if (position == blob.size) { + controller.close(); + } + }); + } + }); + } + } catch (e) { + try { + new Response('').body.getReader().read(); + stream = function stream() { + return new Response(this).body; + } + } catch (e) { + stream = function stream() { + throw new Error('Include https://github.com/MattiasBuelens/web-streams-polyfill'); + } + } + } + } + + + if (!Blob.prototype.arrayBuffer) { + Blob.prototype.arrayBuffer = function arrayBuffer() { + var fr = new FileReader(); + fr.readAsArrayBuffer(this); + return promisify(fr); + } + } + + if (!Blob.prototype.text) { + Blob.prototype.text = function text() { + var fr = new FileReader(); + fr.readAsText(this); + return promisify(fr); + } + } + + if (!Blob.prototype.stream) { + Blob.prototype.stream = stream; + } + BlobBuilderConstructor.prototype = Blob.prototype; BlobConstructor.prototype = Blob.prototype; }