Created
November 1, 2021 18:51
-
-
Save Explosion-Scratch/357c2eebd8254f8ea5548b0e6ac7a61b to your computer and use it in GitHub Desktop.
Compress string using gzip and native browser APIs
This file contains hidden or 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
function compress(string, encoding) { | |
const byteArray = new TextEncoder().encode(string); | |
const cs = new CompressionStream(encoding); | |
const writer = cs.writable.getWriter(); | |
writer.write(byteArray); | |
writer.close(); | |
return new Response(cs.readable).arrayBuffer(); | |
} | |
function decompress(byteArray, encoding) { | |
const cs = new DecompressionStream(encoding); | |
const writer = cs.writable.getWriter(); | |
writer.write(byteArray); | |
writer.close(); | |
return new Response(cs.readable).arrayBuffer().then(function (arrayBuffer) { | |
return new TextDecoder().decode(arrayBuffer); | |
}); | |
} |
@Explosion-Scratch So I've found a way to catch the error message. Apparently it's in the writer
's Promise. I still dont know if it is the correct way, but it's one of those moments of "Dont know how or why it works, but it works". If you or anyone else understand more about it, please correct my codes.
async function decomp(str,mode="gzip"){
// Using Node Buffer for encoder
str = Buffer.from(str, "base64")
const cs = new DecompressionStream(mode)
const writer = cs.writable.getWriter()
writer.write(str)
writer.close()
return await new Response(cs.readable).arrayBuffer()
.then(
// Resolve Function
arr=>(Buffer.from(arr)).toString("utf8"),
// Reject Function
async _=>{throw new Error(await Promise.reject(await writer.closed))}
)
}
let string = [
// "These strings were compressed!" compressed with gzip and base64 encoder
`H4sIAAAAAAAACgvJSC1OVSguKcrMSy9WKE8tSlVIzs8tKEotLk5NUQQAfREzrR4AAAA`,
// Change capital R near the end
`H4sIAAAAAAAACgvJSC1OVSguKcrMSy9WKE8tSlVIzs8tKEotLk5NUQQAfREzrr4AAAA`,
// Change 1 char at the end
`H4sIAAAAAAAACgvJSC1OVSguKcrMSy9WKE8tSlVIzs8tKEotLk5NUQQAfREzrR4AAAx`,
// Add 1 char at the end
`H4sIAAAAAAAACgvJSC1OVSguKcrMSy9WKE8tSlVIzs8tKEotLk5NUQQAfREzrR4AAAAx`,
],
result = []
console.clear()
for(let item of string){
try{
result.push(
"Succesfully decompressing!\n\n" + "String Result : "+ (await decomp(item))
)
}
catch(err){
result.push("Failed to decompress!\n\n"+ err.name +" : "+ err.message)
}
}
console.log(result.join("\n\n=====================================================================\n\n"))
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@Explosion-Scratch I appreciate your times and your replies, Sir.
Cheers