Open in a new tab

Compress a textarea's text with gzip and raw deflate, show the sizes and ratios, and check that decompressing gives the exact bytes back.

Uses @awacloud/fw (Apache-2.0). This example's code is Apache-2.0.

When to use it

You store or send text-like data and want it smaller without a server: gzip for anything another tool will read (.gz files, HTTP bodies), raw deflate when you control both ends and the 18 bytes of gzip framing matter.

Copy-paste steps

  1. npm install @awacloud/fw
  2. Serve node_modules/@awacloud/fw/src/ at /vendor/fw/ (node serve.js from the examples root does this; any static server works).
  3. Copy index.html and main.js next to each other and open index.html through that server. The ../../_style/examples.css link is optional: copy that file along, or delete the link.
  4. For inputs above a few hundred kilobytes, switch to the async gzip / gunzip pair (gzipRoundTrip shows it) so the page stays responsive.

What it shows

  • gzip.gzipSync(bytes, { level }) / gunzipSync, and deflate.deflateSync / inflateSync: byte in, byte out, no streams needed for small inputs.
  • registerAllDeep([gzip, deflate]) pulls crc32, bitstream, huffman and lz77 along through the descriptors' deps.
  • A byte-for-byte comparison of the restored data, not a string compare.
  • gunzip on bytes received from elsewhere: a corrupted stream throws, so wrap it where the input is not yours.

Code

main.js

javascriptApache-2.072 lines

// SPDX-License-Identifier: Apache-2.0
import fw from '@awacloud/fw';
import { gzip } from '@awacloud/fw/io/compress/gzip.js';
import { deflate } from '@awacloud/fw/io/compress/deflate.js';

fw.runtime.registerAllDeep([gzip, deflate]);
const GZIP = fw.runtime.resolve('gzip');
const DEFLATE = fw.runtime.resolve('deflate');
const LEVEL = 6;

/**
 * @typedef {{ format: string, bytes: number, ratio: number, restored: boolean }} Row
 */

/**
 * Compress the UTF-8 bytes of `text` both ways and decompress each result.
 * @param {string} text
 * @returns {{ original: number, rows: Row[] }}
 */
export function compare(text) {
    const original = new TextEncoder().encode(text);
    /** @param {string} format @param {Uint8Array} out @param {Uint8Array} back @returns {Row} */
    function row(format, out, back) {
        const restored = back.length === original.length && back.every((b, i) => b === original[i]);
        return { format, bytes: out.length, ratio: original.length ? out.length / original.length : 1, restored };
    }
    const gz = GZIP.gzipSync(original, { level: LEVEL });
    const raw = DEFLATE.deflateSync(original, { level: LEVEL });
    return {
        original: original.length,
        rows: [
            row('gzip', gz, GZIP.gunzipSync(gz)),
            row('deflate (raw)', raw, DEFLATE.inflateSync(raw)),
        ],
    };
}

/**
 * The async variants for larger inputs (they yield between blocks).
 * @param {Uint8Array} bytes
 * @returns {Promise<Uint8Array>}
 */
export async function gzipRoundTrip(bytes) {
    return GZIP.gunzip(await GZIP.gzip(bytes, { level: LEVEL }));
}

/**
 * Decompress bytes received from elsewhere: a corrupted stream throws.
 * @param {Uint8Array} bytes
 * @returns {Uint8Array}
 * @throws {Error} on a corrupted stream
 */
export const gunzip = (bytes) => GZIP.gunzipSync(bytes);

const input = /** @type {HTMLTextAreaElement} */ (document.getElementById('input'));
const rows = /** @type {HTMLElement} */ (document.getElementById('rows'));
const status = /** @type {HTMLElement} */ (document.getElementById('status'));

function update() {
    const result = compare(input.value);
    rows.replaceChildren(...result.rows.map((r) => {
        const tr = document.createElement('tr');
        const percent = `${Math.round(r.ratio * 100)}%`;
        const cells = [r.format, String(r.bytes), percent, r.restored ? 'identical' : 'DIFFERENT'];
        for (const cell of cells) tr.appendChild(document.createElement('td')).textContent = cell;
        return tr;
    }));
    status.textContent = `${result.original} bytes of UTF-8 text`;
}

input.addEventListener('input', update);
update();

index.html

htmlApache-2.031 lines

<!doctype html>
<!-- SPDX-License-Identifier: Apache-2.0 -->
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>fw · Compress text with gzip and deflate</title>
  <link rel="stylesheet" href="../../_style/examples.css">
  <script type="importmap">
  { "imports": {
    "@awacloud/fw": "/vendor/fw/main.js", "@awacloud/fw/": "/vendor/fw/" } }
  </script>
  <script type="module" src="./main.js"></script>
</head>
<body>
  <main>
    <h1>Compress text with gzip and deflate</h1>
    <label for="input">Text</label>
    <textarea id="input" rows="4">The quick brown fox jumps over the lazy dog.
The quick brown fox jumps over the lazy dog.
The quick brown fox jumps over the lazy dog.</textarea>
    <table>
      <caption>Bytes before and after compression (level 6)</caption>
      <thead><tr><th scope="col">Format</th><th scope="col">Bytes</th><th scope="col">Ratio</th>
        <th scope="col">Round trip</th></tr></thead>
      <tbody id="rows"></tbody>
    </table>
    <p id="status" aria-live="polite"></p>
  </main>
</body>
</html>