Skip to content

Instantly share code, notes, and snippets.

@mizchi
Last active April 22, 2022 12:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mizchi/721d781d02ed821ad6dd7283b512b0b8 to your computer and use it in GitHub Desktop.
Save mizchi/721d781d02ed821ad6dd7283b512b0b8 to your computer and use it in GitHub Desktop.
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();
@mizchi
Copy link
Author

mizchi commented Apr 22, 2022

await new Response(new Blob([new TextEncoder().encode(JSON.stringify({"hello": "world"}))]).stream().pipeThrough(new CompressionStream("gzip"))).arrayBuffer()

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