Skip to content

Instantly share code, notes, and snippets.

@duhaime
Last active June 18, 2020 12:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save duhaime/081ffb6e2f8487cbbe70b0112cf47908 to your computer and use it in GitHub Desktop.
Save duhaime/081ffb6e2f8487cbbe70b0112cf47908 to your computer and use it in GitHub Desktop.
gunzip js gzip
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<title>title</title>
</head>
<body></body>
<script src='gunzip.min.js'></script>
<script type='text/javascript'>
function get(url, onSuccess, onErr, onProgress) {
var xhr = new XMLHttpRequest();
xhr.overrideMimeType('text\/plain; charset=x-user-defined');
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
if (xhr.status === 200) {
if (onSuccess) onSuccess(xhr.responseText)
} else {
if (onErr) onErr(xhr)
}
};
};
xhr.onprogress = function() {
if (onProgress) onProgress(e);
};
xhr.open('GET', url, true);
xhr.send();
}
/**
* file created in python via:
*
* import gzip
* with gzip.GzipFile('gzipped.json.gz', 'w') as out:
* out.write(json.dumps({'cats': 2}).encode('utf-8'))
**/
get('gzipped.json.gz', function(data) {
// Step character by character through file data and append to bytes
var bytes = [];
for (var i=0; i<data.length; i++) {
bytes.push(data.charCodeAt(i) & 0xff);
}
// Zlib is from https://github.com/imaya/zlib.js
var gunzip = new Zlib.Gunzip(bytes);
var plain = gunzip.decompress();
// Create ascii string from byte sequence
var asciistring = '';
for (var i=0; i<plain.length; i++) {
asciistring += String.fromCharCode(plain[i]);
}
console.log(asciistring)
})
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment