Skip to content

Back to Snippets

compress()

Compresses a JavaScript string with a GZIP CompressionStream, and returns a base64 representation.

/*
	Usage: await compress('my string');
*/
async function compress(str) {
	const resp = new Response(
		new Blob([str])
			.stream()
			.pipeThrough(
				new CompressionStream('gzip')
			)
	);
	return (await resp.bytes()).toBase64();
}

To decompress the base64 representation, the opposite operation uses DecompressionStream:

async function decompress(str) {
	return new Response(
		new Blob([Uint8Array.fromBase64(str)])
			.stream()
			.pipeThrough(
				new DecompressionStream('gzip')
			)
	).text();
}

Note that base64 encoding is not safe for filenames and URL segments, since it uses + and / as its last two, non-alphanumeric characters. RFC 4648 § 5 defines a variant that instead uses - and _ respectively and makes the padding character = optional, but the variant is not implemented in web APIs.