Skip to content

Instantly share code, notes, and snippets.

@kuanyui
Last active October 16, 2020 01:44
Show Gist options
  • Save kuanyui/ebb04934340cbaee23b804b9f3c39ebb to your computer and use it in GitHub Desktop.
Save kuanyui/ebb04934340cbaee23b804b9f3c39ebb to your computer and use it in GitHub Desktop.
export const JsonFileIo = {
/**
* NOTE: This function works smoothly on Firefox, but crash on Chromium.
* I don't know why, but DON'T USE
*/
read(): Promise<any> {
return new Promise((resolve, reject) => {
const inputEl = document.createElement("input")
inputEl.type = 'file'
document.body.appendChild(inputEl)
inputEl.addEventListener('input', (ev) => {
console.log('input change', ev)
JsonFileIo.readFromInputElementEvent(ev as InputEvent).then((r) => {
resolve(r)
window.setTimeout(() => inputEl.remove(), 1000)
}).catch(err => {
console.log('error occurred:', err)
resolve(err)
window.setTimeout(() => inputEl.remove(), 1000)
})
})
inputEl.click()
})
},
readFromInputElement: function (inputEl: HTMLInputElement): Promise<any> {
if (!inputEl) { throw new Error('[To Developer] Bug!') }
return new Promise((resolve, reject) => {
if (!inputEl.files) { return reject('No file found.') }
const file = inputEl.files[0]
if (file) {
let reader = new FileReader()
reader.onload = () => {
try {
const obj = JSON.parse(reader.result as string)
return resolve(obj)
} catch (err) {
return reject(err)
}
}
reader.readAsText(file)
}
})
},
readFromInputElementEvent: function (ev: InputEvent): Promise<any> {
const inputEl = ev.target as HTMLInputElement
if (!inputEl) { throw new Error('[To Developer] Bug!') }
return JsonFileIo.readFromInputElement(inputEl)
},
downloadAsFile: function (jsonObj: object) {
const aEl = document.createElement("a")
document.body.appendChild(aEl)
aEl.style.display = 'none'
let blob = new Blob([JSON.stringify(jsonObj, null, 2)], { type: 'text/plain' })
let downloadUrl = window.URL.createObjectURL(blob)
const d = new Date()
const YYYY = (d.getFullYear() + '')
const MM = (d.getMonth() + '').padStart(2, '0')
const DD = (d.getDate() + '').padStart(2, '0')
const hh = (d.getHours() + '').padStart(2, '0')
const mm = (d.getMinutes() + '').padStart(2, '0')
const ss = (d.getSeconds() + '').padStart(2, '0')
let fileName = `${YYYY}${MM}${DD}-${hh}${mm}${ss}.json`
aEl.href = downloadUrl
aEl.download = fileName
aEl.click()
window.URL.revokeObjectURL(downloadUrl)
aEl.remove()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment