compression icon indicating copy to clipboard operation
compression copied to clipboard

Add a one-shot method?

Open ricea opened this issue 6 years ago • 3 comments
trafficstars

Maybe we should have something like

static Promise<Uint8Array> compress(DOMString format, BufferSource input);

in CompressionStream, and a similar API for DecompressionStream, to make one-shot compression and decompression easier to do.

ricea avatar Oct 15 '19 05:10 ricea

It would be convenient to be able to do this in one shot.

That said, the current implementation is flexible.

This is my current usage to compress data for sharing in a URL hash for open checklist

/**
* converts text to gzip compressed hexText
* @param {string} text - a string
* @returns {Promise<string>} gzip compressed hexText
*/
async function compress(text) {
   // https://developer.mozilla.org/en-US/docs/Web/API/CompressionStream

   const readStream = new Response(text);
   const compressedReadableStream = readStream.body.pipeThrough(new CompressionStream("gzip"));
   const response = new Response(compressedReadableStream);

   const buffer = await response.arrayBuffer();
   const compressedHexText = convertBufferToHex(buffer);
   return compressedHexText;
}

wandyezj avatar Nov 27 '22 04:11 wandyezj

@wandyezj Thank you for your use case.

Using a Response to convert a stream to an array buffer is convenient, but inefficient. See https://wicg.github.io/compression/#example-deflate-compress for a faster way to do it.

ricea avatar Nov 28 '22 08:11 ricea

I'm using the Compression API to encode data for URL fragments, a one-shot method would be really nice to have compared to piping the text through multiple streams to get there.

gtm-nayan avatar Aug 15 '23 04:08 gtm-nayan