CompressionStream Round Trips Text
Compress and decompress strings with CompressionStream and DecompressionStream, piping through Blob so no third-party codec is needed.
Code
async function compress(text) {
const stream = new Blob([text]).stream().pipeThrough(new CompressionStream('gzip'));
return new Response(stream).arrayBuffer();
}
async function decompress(buffer) {
const stream = new Blob([buffer]).stream().pipeThrough(new DecompressionStream('gzip'));
return new Response(stream).text();
}
const original = 'devexamples '.repeat(200);
const packed = await compress(original);
const restored = await decompress(packed);
console.log('original bytes:', original.length);
console.log('compressed bytes:', packed.byteLength);
console.log('restored matches:', restored === original);Output
Captured from a sandboxed run of this snippet in the build pipeline.
original bytes: 2400
compressed bytes: 52
restored matches: trueHow the snippet works
CompressionStream Round Trips Text comes down to the functions compress and decompress.
Await points sequence the asynchronous work; a rejection lands at the awaiting line.
The return value is newly constructed — inputs are never handed back.
Applying it
Signature: async function compress(text)
Look for the original bytes:, compressed bytes:, restored matches: prefixes when the file runs; they tie each line to its step.
Statements that matter
return new Response(stream).arrayBuffer();
const restored = await decompress(packed);
const packed = await compress(original);
Interactive Tools for This Topic
FAQ
- Does `compress` modify its input?
- No mutation happens — the function reads its input and returns a new value.
- Does this require external packages?
- No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. The file defines `compress`, `decompress` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.