Skip to content

Instantly share code, notes, and snippets.

@alexis-martel
Last active April 30, 2024 08:55
Show Gist options
  • Save alexis-martel/f70aaae9239b1e1a4a9eee8cf8f30b46 to your computer and use it in GitHub Desktop.
Save alexis-martel/f70aaae9239b1e1a4a9eee8cf8f30b46 to your computer and use it in GitHub Desktop.
How to use the native Compression Streams API to compress and decompress strings in JavaScript
async function compressAndEncode(inputString) {
const encoder = new TextEncoder();
// Create a ReadableStream from the input string
const inputReadableStream = new ReadableStream({
start(controller) {
controller.enqueue(encoder.encode(inputString));
controller.close();
}
});
// Compress the ReadableStream using the gzip algorithm
const compressedStream = inputReadableStream.pipeThrough(new CompressionStream("gzip"));
// Read the compressed data from the stream
const reader = compressedStream.getReader();
let compressedData = new Uint8Array();
let result;
while ((result = await reader.read())) {
if (result.done) {
// Encode the compressed data as a URI component
const encodedData = encodeURIComponent(btoa(String.fromCharCode(...compressedData)));
return encodedData;
} else {
compressedData = new Uint8Array([...compressedData, ...result.value]);
}
}
}
async function decompressAndDecode(encodedString) {
const decoder = new TextDecoder();
// Decode the URI-encoded compressed data
const decodedData = atob(decodeURIComponent(encodedString));
// Convert the decoded data to a Uint8Array
const compressedData = new Uint8Array(decodedData.split("").map((c) => c.charCodeAt(0)));
// Create a ReadableStream from the compressed data
const compressedStream = new ReadableStream({
start(controller) {
controller.enqueue(compressedData);
controller.close();
}
});
// Decompress the ReadableStream using the gzip algorithm
const decompressedStream = compressedStream.pipeThrough(new DecompressionStream("gzip"));
// Read the decompressed data from the stream
const reader = decompressedStream.getReader();
let decompressedData = "";
let result;
while ((result = await reader.read())) {
if (result.done) {
return decompressedData;
} else {
decompressedData += decoder.decode(result.value);
}
}
}
// Usage
(async function() {
let x = await compressAndEncode("Hello, World!");
console.log(x);
let y = await decompressAndDecode(x);
console.log(y);
})();
@thk100
Copy link

thk100 commented Jan 16, 2024

Dear Alexis,
I would like to use this code in my App "MintApps" (https://codeberg.org/MintApps/client) which is under GPL3.
Would this be ok?
Best regards,
Thomas

@alexis-martel
Copy link
Author

alexis-martel commented Jan 16, 2024

@thk100: Yes, it would be totally fine, that's why I published it here!
Enjoy!

@thk100
Copy link

thk100 commented Jan 16, 2024

Thank you!

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