DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Lucas Damian Johnson
Lucas Damian Johnson

Posted on

Compress & Decompress An ArrayBuffer Client Side in JS

The Compressions Streams API is new and up and coming way to compress and decompress data in the browser. Please note the support for the API is not very wide so use at your own risk.

I am writing this because I did not find any good examples of just compressing/decompressing an ArrayBuffer which is what I needed the API to do. The following two code snippets show how to do exactly that.

Compress An Array Buffer

const compressArrayBuffer = async (input: ArrayBuffer) => {
  //create the stream
  const cs = new CompressionStream("gzip");
  //create the writer
  const writer = cs.writable.getWriter();
  //write the buffer to the writer 
  writer.write(input);
  writer.close();
  //create the output 
  const output: Uint8Array[] = [];
  const reader = cs.readable.getReader();
  let totalSize = 0;
  //go through each chunk and add it to the output
  while (true) {
    const { value, done } = await reader.read();
    if (done) break;
    output.push(value);
    totalSize += value.byteLength;
  }
  const concatenated = new Uint8Array(totalSize);
  let offset = 0;
  //finally build the compressed array and return it 
  for (const array of output) {
    concatenated.set(array, offset);
    offset += array.byteLength;
  }
  return concatenated;
};

Enter fullscreen mode Exit fullscreen mode

Deeompress An Array Buffer

const  decompressArrayBuffer = async (input: ArrayBuffer): Promise<Uint8Array> =>{
  //create the stream
  const ds = new DecompressionStream("gzip");
  //create the writer
  const writer = ds.writable.getWriter();
  //write the buffer to the writer thus decompressing it 
  writer.write(input);
  writer.close();
  //create the output
  const output: Uint8Array[] = [];
  //create the reader
  const reader = ds.readable.getReader();
  let totalSize = 0;
  //go through each chunk and add it to the output
  while (true) {
   const { value, done } = await reader.read();
   if (done) break;
   output.push(value);
   totalSize += value.byteLength;
  }
  const concatenated = new Uint8Array(totalSize);
  let offset = 0;
  //finally build the compressed array and return it 
  for (const array of output) {
   concatenated.set(array, offset);
   offset += array.byteLength;
  }
  return concatenated;
 }

Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Tired of sifting through your feed?

Find the content you want to see.

Change your feed algorithm by adjusting your experience level and give weights to the tags you follow.