Skip to main content
Baldur Bjarnason

FormData to compressed buffer and back

Baldur Bjarnason

Now that we have native compression streams and since Response is a native method for collecting and parsing all sorts to all sorts, you could use that to serialise FormData objects (with the header) to ArrayBuffer, compress it, and store somewhere, such as with the Origin Private File System.

const formData = new FormData();
formData.append("username", "Chris");
const serialised = new Response(formData);
// You need the headers because they give you the boundary value needed to parse the form data
const headers = serialised.headers;
// You could serialise the headers to arraybuffer as well to store somewhere
// Remember to convert the iterator to an array if that's the method you're using.
console.log(JSON.stringify([...headers.entries()]));
const compressedStream = serialised.body.pipeThrough(
	new CompressionStream("gzip"),
)
// Response is a generic method for collecting byte streams into whaever (UInt8Array, ArrayBuffer, text, JSON, etc)
const bytes = await new Response(compressedStream).bytes();
// This should be compressed. You could compare it to (new Response(formData)).bytes() to get the uncompressed size.
console.log(bytes.length);
const ds = new DecompressionStream("gzip");
const deCompressedStream = new Response(bytes).body.pipeThrough(ds);
const deserialised = new Response(deCompressedStream, {headers});
console.log(await deserialised.formData());