brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: CompressionStream gzips data in the browser without a library

Javascript
~/tips/tip-js-compressionstream-gzip

const stream = new Blob([text]).stream()

Compress a large JSON export or upload with a built-in stream.

A big log or JSON export uploads faster when it is compressed first, and I would rather not ship a compression library for that. Browsers have a gzip stream built in.

async function gzip(text) {
  const stream = new Blob([text]).stream()
    .pipeThrough(new CompressionStream("gzip"));
  return new Response(stream).blob();
}

const packed = await gzip(JSON.stringify(bigData));
await fetch("/api/upload", {
  method: "POST",
  headers: { "Content-Type": "application/gzip" },
  body: packed,
});

CompressionStream is a transform stream: data goes in one side and compressed bytes come out the other. A Blob gives you a readable stream, pipeThrough runs it through the compressor, and wrapping the result in a Response is a short way to collect a stream into a blob. The word “hello ” repeated 1000 times (6000 bytes) comes out at 53 bytes. Real data compresses less, but JSON usually shrinks a lot.

The formats are "gzip", "deflate" and "deflate-raw". DecompressionStream reverses it, for example to read a .gz file a user picks.

Your server has to expect it. I’d send a gzip file as the body with its own content type; sending JSON with Content-Encoding: gzip as a request header only works if the server decompresses request bodies, which many do not by default. Support: Chrome 80, Firefox 113 and Safari 16.4.

Further reading: MDN: CompressionStream, MDN: Compression Streams API

More Javascript tips node --inspect-brk app.js obj?.prop const filePath = String.raw`C:\Development\profile\about.html`; const observer = new ResizeObserver((entries) => { URL.parse("not a url"); // null All Javascript tips (40) All topics

Link