Skip to content

Instantly share code, notes, and snippets.

@AimWhy
Last active March 2, 2025 11:17
Show Gist options
  • Save AimWhy/b4b3f13d0f3fea77af7bae5b0a1227e1 to your computer and use it in GitHub Desktop.
Save AimWhy/b4b3f13d0f3fea77af7bae5b0a1227e1 to your computer and use it in GitHub Desktop.

Revisions

  1. AimWhy revised this gist Mar 2, 2025. 1 changed file with 38 additions and 1 deletion.
    39 changes: 38 additions & 1 deletion getBlobWritable.ts
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,18 @@
    interface BlobWritable {
    getWriter: () => {
    abort: () => Promise<void>;
    close: () => Promise<void>;
    closed: Promise<undefined>;
    desiredSize: number | null;
    ready: Promise<undefined>;
    releaseLock: () => void;
    write: (chunk: Uint8Array) => Promise<void>;
    };
    locked: boolean;
    abort: () => Promise<void>;
    close: () => Promise<void>;
    }

    function getBlobWritable(filename: string, onClose: (result: Blob) => void): BlobWritable {
    let blobParts: Uint8Array[] = [];

    @@ -29,4 +44,26 @@ function getBlobWritable(filename: string, onClose: (result: Blob) => void): Blo
    onClose(new File(blobParts, filename));
    },
    };
    }
    }

    async function pipe(readable: ReadableStream, writable: BlobWritable): Promise<void> {
    const reader = readable.getReader();
    const writer = writable.getWriter();

    let done = false;

    while (!done) {
    const status = await reader.read();

    if (!status.done) {
    await writer.write(status.value);
    }

    done = status.done;
    }

    await reader.closed;
    await writer.close();
    }

    // (source.pipeTo && source.pipeTo(destination, { signal: abortController?.signal })) || pipe(source, destination)
  2. AimWhy created this gist Mar 2, 2025.
    32 changes: 32 additions & 0 deletions getBlobWritable.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,32 @@
    function getBlobWritable(filename: string, onClose: (result: Blob) => void): BlobWritable {
    let blobParts: Uint8Array[] = [];

    return {
    getWriter: () => {
    return {
    abort: async () => {
    blobParts = [];
    },
    close: async () => {
    onClose(new File(blobParts, filename));
    },
    closed: Promise.resolve(undefined),
    desiredSize: 3 * 1024 * 1024,
    ready: Promise.resolve(undefined),
    releaseLock: () => {
    // no op
    },
    write: async (chunk) => {
    blobParts.push(chunk);
    },
    };
    },
    locked: false,
    abort: async () => {
    blobParts = [];
    },
    close: async () => {
    onClose(new File(blobParts, filename));
    },
    };
    }