whatwg / compression

Compression Standard
https://compression.spec.whatwg.org/
Other
85 stars 21 forks source link

Add a one-shot method? #8

Open ricea opened 4 years ago

ricea commented 4 years ago

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.

wandyezj commented 1 year ago

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;
}
ricea commented 1 year ago

@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.

gtm-nayan commented 1 year ago

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.