Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save paulroth3d/f391b6f78920a938d9db0ec9db8a5d07 to your computer and use it in GitHub Desktop.
Save paulroth3d/f391b6f78920a938d9db0ec9db8a5d07 to your computer and use it in GitHub Desktop.

Overview

Useful for snippets if you want to merge in additional data

Exporting

Calling the downloadData() function will immediately create a file download (as though you right clicked to download the file within the browser) for the data you provide - in JSON format.

Importing

When you run this script:

  1. A file dialog opens up requesting a file
  2. It reads the file in a plain text
  3. It parses the file as JSON
  4. you can then do what you want with the JSON
/* Auxiliary function to download a file with the exported data */
function downloadData(filename, data) {
const file = new File([data], { type: 'text/json' });
const elem = document.createElement('a');
elem.href = URL.createObjectURL(file);
elem.download = filename;
elem.click();
}
// downloadData('someFile', JSON.stringify(objectToExport));
(async function importFile() {
/* Auxiliary function to open a file selection dialog */
function selectFileToRead() {
return new Promise((resolve) => {
const input = document.createElement('input');
input.setAttribute('type', 'file');
input.addEventListener('change', (e) => {
resolve(e.target.files[0]);
}, false);
input.click();
});
}
/* Auxiliary function to read data from a file */
function readFile(file) {
return new Promise((resolve) => {
const reader = new FileReader();
reader.addEventListener('load', (e) => {
resolve(e.target.result);
});
reader.readAsText(file);
});
}
const file = await selectFileToRead();
const content = await readFile(file);
let jsonContents = JSON.parse(content);
console.log(`found: jsonContents - and do with it what you will}`);
// add your code here...
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment