|
Last change
on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 13 days ago |
|
Fix frontend appearance
|
-
Property mode
set to
100644
|
|
File size:
1.7 KB
|
| Line | |
|---|
| 1 | export const streamChunk = function* (chunk, chunkSize) {
|
|---|
| 2 | let len = chunk.byteLength;
|
|---|
| 3 |
|
|---|
| 4 | if (!chunkSize || len < chunkSize) {
|
|---|
| 5 | yield chunk;
|
|---|
| 6 | return;
|
|---|
| 7 | }
|
|---|
| 8 |
|
|---|
| 9 | let pos = 0;
|
|---|
| 10 | let end;
|
|---|
| 11 |
|
|---|
| 12 | while (pos < len) {
|
|---|
| 13 | end = pos + chunkSize;
|
|---|
| 14 | yield chunk.slice(pos, end);
|
|---|
| 15 | pos = end;
|
|---|
| 16 | }
|
|---|
| 17 | };
|
|---|
| 18 |
|
|---|
| 19 | export const readBytes = async function* (iterable, chunkSize) {
|
|---|
| 20 | for await (const chunk of readStream(iterable)) {
|
|---|
| 21 | yield* streamChunk(chunk, chunkSize);
|
|---|
| 22 | }
|
|---|
| 23 | };
|
|---|
| 24 |
|
|---|
| 25 | const readStream = async function* (stream) {
|
|---|
| 26 | if (stream[Symbol.asyncIterator]) {
|
|---|
| 27 | yield* stream;
|
|---|
| 28 | return;
|
|---|
| 29 | }
|
|---|
| 30 |
|
|---|
| 31 | const reader = stream.getReader();
|
|---|
| 32 | try {
|
|---|
| 33 | for (;;) {
|
|---|
| 34 | const { done, value } = await reader.read();
|
|---|
| 35 | if (done) {
|
|---|
| 36 | break;
|
|---|
| 37 | }
|
|---|
| 38 | yield value;
|
|---|
| 39 | }
|
|---|
| 40 | } finally {
|
|---|
| 41 | await reader.cancel();
|
|---|
| 42 | }
|
|---|
| 43 | };
|
|---|
| 44 |
|
|---|
| 45 | export const trackStream = (stream, chunkSize, onProgress, onFinish) => {
|
|---|
| 46 | const iterator = readBytes(stream, chunkSize);
|
|---|
| 47 |
|
|---|
| 48 | let bytes = 0;
|
|---|
| 49 | let done;
|
|---|
| 50 | let _onFinish = (e) => {
|
|---|
| 51 | if (!done) {
|
|---|
| 52 | done = true;
|
|---|
| 53 | onFinish && onFinish(e);
|
|---|
| 54 | }
|
|---|
| 55 | };
|
|---|
| 56 |
|
|---|
| 57 | return new ReadableStream(
|
|---|
| 58 | {
|
|---|
| 59 | async pull(controller) {
|
|---|
| 60 | try {
|
|---|
| 61 | const { done, value } = await iterator.next();
|
|---|
| 62 |
|
|---|
| 63 | if (done) {
|
|---|
| 64 | _onFinish();
|
|---|
| 65 | controller.close();
|
|---|
| 66 | return;
|
|---|
| 67 | }
|
|---|
| 68 |
|
|---|
| 69 | let len = value.byteLength;
|
|---|
| 70 | if (onProgress) {
|
|---|
| 71 | let loadedBytes = (bytes += len);
|
|---|
| 72 | onProgress(loadedBytes);
|
|---|
| 73 | }
|
|---|
| 74 | controller.enqueue(new Uint8Array(value));
|
|---|
| 75 | } catch (err) {
|
|---|
| 76 | _onFinish(err);
|
|---|
| 77 | throw err;
|
|---|
| 78 | }
|
|---|
| 79 | },
|
|---|
| 80 | cancel(reason) {
|
|---|
| 81 | _onFinish(reason);
|
|---|
| 82 | return iterator.return();
|
|---|
| 83 | },
|
|---|
| 84 | },
|
|---|
| 85 | {
|
|---|
| 86 | highWaterMark: 2,
|
|---|
| 87 | }
|
|---|
| 88 | );
|
|---|
| 89 | };
|
|---|
Note:
See
TracBrowser
for help on using the repository browser.