Skip to content

Instantly share code, notes, and snippets.

@Explosion-Scratch
Created November 1, 2021 18:51
Show Gist options
  • Save Explosion-Scratch/357c2eebd8254f8ea5548b0e6ac7a61b to your computer and use it in GitHub Desktop.
Save Explosion-Scratch/357c2eebd8254f8ea5548b0e6ac7a61b to your computer and use it in GitHub Desktop.
Compress string using gzip and native browser APIs
function compress(string, encoding) {
const byteArray = new TextEncoder().encode(string);
const cs = new CompressionStream(encoding);
const writer = cs.writable.getWriter();
writer.write(byteArray);
writer.close();
return new Response(cs.readable).arrayBuffer();
}
function decompress(byteArray, encoding) {
const cs = new DecompressionStream(encoding);
const writer = cs.writable.getWriter();
writer.write(byteArray);
writer.close();
return new Response(cs.readable).arrayBuffer().then(function (arrayBuffer) {
return new TextDecoder().decode(arrayBuffer);
});
}
@USMortality
Copy link

USMortality commented Sep 10, 2023

You should be able to use it like this:

const compressed = await(“hello world”, “utf-8”)
const decompressed = await decompress(compressed)

(Not tested; sent from my phone)

@TCH68k
Copy link

TCH68k commented Sep 11, 2023

Yep, works:

function compress(string, encoding) {
  const byteArray = new TextEncoder().encode(string);
  const cs = new CompressionStream(encoding);
  const writer = cs.writable.getWriter();
  writer.write(byteArray);
  writer.close();
  return new Response(cs.readable).arrayBuffer();
}

function promptDownload(filename, content, mimetype)
{
	if (mimetype === undefined)
	{
		mimetype = 'application/octet-stream';
	}

	var a = window.document.createElement('A');
	a.href = window.URL.createObjectURL(new Blob([content], {type: mimetype}));
	a.download = filename;
	document.body.appendChild(a);
	a.click();
	document.body.removeChild(a);
}

async function do_stuff()
{
	const s = "Árvíztűrő tükörfúrógép\n";
	var c = await compress(s + s + s + s + s + s + s + s, 'gzip');
	promptDownload('stuff.txt.gz', c);
}
do_stuff();

Thank you for the help and Explosion-Scratch for writing it.

@Explosion-Scratch
Copy link
Author

No problem @TCH68k - Happy to help, mention me if you want help with anything lol

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment