Skip to content

Instantly share code, notes, and snippets.

@asidko
Created April 20, 2022 14:00
Show Gist options
  • Select an option

  • Save asidko/9c7064027039411a11323eaf7d8ea2a4 to your computer and use it in GitHub Desktop.

Select an option

Save asidko/9c7064027039411a11323eaf7d8ea2a4 to your computer and use it in GitHub Desktop.

Revisions

  1. asidko created this gist Apr 20, 2022.
    46 changes: 46 additions & 0 deletions gzip.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,46 @@
    // Paste the following example to browser console


    // Comppreses string to GZIP. Retruns a Promise with Base64 string
    const compress = string => {
    const blobToBase64 = blob => new Promise((resolve, _) => {
    const reader = new FileReader();
    reader.onloadend = () => resolve(reader.result.split(',')[1]);
    reader.readAsDataURL(blob);
    });
    const byteArray = new TextEncoder().encode(string);
    const cs = new CompressionStream('gzip');
    const writer = cs.writable.getWriter();
    writer.write(byteArray);
    writer.close();
    return new Response(cs.readable).blob().then(blobToBase64);
    };

    // Decompresses base64 encoded GZIP string. Retruns a string with original text.
    const decompress = base64string => {
    const bytes = Uint8Array.from(atob(base64string), c => c.charCodeAt(0));
    const cs = new DecompressionStream('gzip');
    const writer = cs.writable.getWriter();
    writer.write(bytes);
    writer.close();
    return new Response(cs.readable).arrayBuffer().then(function (arrayBuffer) {
    return new TextDecoder().decode(arrayBuffer);
    });
    }

    /////////////////////
    // Checking
    /////////////////////
    Promise.resolve("Hello GZIP!")
    .then(v => {
    console.log("Original value: %s", v);
    return v;
    })
    .then(v => compress(v))
    .then(v => {
    console.log("Compressed value: %s", v);
    return v;
    })
    .then(v => decompress(v))
    .then(v => console.log("Decomporessed value: %s", v));