Skip to content

Instantly share code, notes, and snippets.

@xeolabs
Forked from w1ndy/BlobInflator.js
Created June 9, 2021 17:29
Show Gist options
  • Save xeolabs/1ab512cc346c330e4fe98d9f4e7e11d3 to your computer and use it in GitHub Desktop.
Save xeolabs/1ab512cc346c330e4fe98d9f4e7e11d3 to your computer and use it in GitHub Desktop.
Inflate gzipped JSON blobs in JavaScript with pako and WebWorker (worker-loader via Webpack)
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 })
})
}
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)
})
export function randomString () {
return '$' + Math.random().toString(36).slice(2, 10)
}
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