Created
May 17, 2017 11:05
-
-
Save AntoineMurat/b9ee941b35e4495716b3103bb8bbcedb to your computer and use it in GitHub Desktop.
[HTML5 / JS / 2017] Load JSON/text file client-side (promise or callback)
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
/* | |
* Load an object from a JSON file on client's computer. | |
*/ | |
const loadJSON = callback => { | |
if (callback) | |
return loadJSONCallback(callback) | |
return loadJSONPromise() | |
} | |
const loadJSONCallback = callback => { | |
const input = document.createElement('input') | |
input.setAttribute('type', 'file') | |
input.style.display = 'none' | |
input.addEventListener('change', event => { | |
// Cancel detection not working, I don't know how to make it worK. | |
if (input.value.length === 0) | |
callback(null, true) | |
else { | |
const file = input.files[0] | |
const reader = new FileReader() | |
reader.onload = event => { | |
callback(JSON.parse(atob(event.target.result.split(',').pop())), false) | |
} | |
reader.readAsDataURL(file) | |
} | |
document.body.removeChild(input) | |
}) | |
document.body.appendChild(input) | |
input.click() | |
} | |
const loadJSONPromise = () => new Promise((resolve, reject) => { | |
loadJSONCallback((object, err) => err ? reject('Load canceled.') : resolve(object)) | |
}) | |
// How to use : | |
// Callback | |
loadJSON( (data, err) => { | |
if (err) | |
return console.error(`Error: ${err}`) | |
console.info(data) | |
}) | |
// Promise | |
loadJSON().then( | |
data => console.info(data) | |
).catch( | |
err => console.error(err) | |
) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment