Skip to content

Instantly share code, notes, and snippets.

@mizchi
Last active Jun 18, 2021
Embed
What would you like to do?
declare const DecompressionStream: any;
declare const CompressionStream: any;
const encoder = new TextEncoder();
const decoder = new TextDecoder();
async function compress(str: string): Promise<ArrayBuffer> {
const cs = new CompressionStream("gzip");
const buf = encoder.encode(str);
const stream = new Response(buf).body!.pipeThrough(cs);
return new Response(stream as any).arrayBuffer();
}
async function decompress(buffer: ArrayBuffer): Promise<string> {
const ds = new DecompressionStream("gzip");
const decompressedStream = new Blob([buffer]).stream().pipeThrough(ds);
const buf = await new Response(decompressedStream as any).arrayBuffer();
return decoder.decode(buf);
}
async function main() {
const json = { a: 1 };
const str = JSON.stringify(json);
const compressed = await compress(str);
const restored = await decompress(compressed);
console.assert(str === restored);
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment