Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support new reading methods #18

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
104 changes: 104 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down