Last active
April 30, 2024 08:55
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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