Last active
June 9, 2021 17:29
-
-
Save w1ndy/664c8113164b159c0dfd73f85eec36e8 to your computer and use it in GitHub Desktop.
Inflate gzipped JSON blobs in JavaScript with pako and WebWorker (worker-loader via Webpack)
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
import { randomString } from './Helpers' | |
import BlobInflatorWorker from './BlobInflator.worker' | |
const worker = new BlobInflatorWorker() | |
const handlers = {} | |
worker.onmessage = function (e) { | |
if (!e.data.error) { | |
handlers[e.data.key].resolve(e.data.json) | |
} else { | |
handlers[e.data.key].reject(e.data.msg) | |
} | |
} | |
export async function inflateBlob (blob) { | |
const key = randomString() | |
return new Promise((resolve, reject) => { | |
handlers[key] = { resolve, reject } | |
worker.postMessage({ key, blob }) | |
}) | |
} |
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
import pako from 'pako' | |
self.addEventListener('message', function ({ data: { key, blob } }) { | |
const reader = new FileReader() | |
reader.onload = e => { | |
try { | |
const json = JSON.parse(pako.inflate(e.target.result, { to: 'string' })) | |
postMessage({ key, json }) | |
} catch (err) { | |
postMessage({ error: true, msg: err.toString() }) | |
} | |
} | |
reader.readAsArrayBuffer(blob) | |
}) |
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
export function randomString () { | |
return '$' + Math.random().toString(36).slice(2, 10) | |
} |
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
import Vue from 'vue' | |
import VueResource from 'vue-resource' | |
import { inflateBlob } from './BlobInflator' | |
Vue.use(VueResource) | |
const resp = await Vue.http.get('test.json.gz', { responseType: 'blob' }) | |
const json = await inflateBlob(await resp.blob()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment