Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save SebastianUdden/421637164d0ad5e1804d3fb0d18e9256 to your computer and use it in GitHub Desktop.

Select an option

Save SebastianUdden/421637164d0ad5e1804d3fb0d18e9256 to your computer and use it in GitHub Desktop.
Import and export localstorage to file for sharing and backup
const createFile = (data, filename, type) => {
const file = new Blob([data], { type: type });
var a = document.createElement("a"),
url = URL.createObjectURL(file);
a.href = url;
a.download = filename;
a.style.color = "white";
const exportEl = document.getElementById("export");
if (exportEl) {
exportEl.style.marginTop = "15px";
exportEl.style.marginBottom = "15px";
var text = document.createTextNode(filename);
a.appendChild(text);
exportEl.innerHTML = "";
exportEl.appendChild(a);
}
};
const addZero = (value) => {
const number = Number.parseInt(value);
return number < 10 ? `0${number}` : number;
};
const formatFileName = (key) => {
const now = new Date();
const year = now.getUTCFullYear();
const month = addZero(now.getUTCMonth());
const date = addZero(now.getUTCDate());
const hours = addZero(now.getUTCHours());
const minutes = addZero(now.getUTCMinutes());
return `${key}-${year}-${month}-${date}_${hours}-${minutes}.json`;
};
// <button onClick={() => exportData("new-tag")}>Export</button>
// <div id="export" />
export const exportData = (key) => {
const data = localStorage.getItem(key);
const filename = formatFileName(key);
createFile(JSON.stringify(data), filename, "application/json");
};
const saveAndReload = (key, blob) => {
localStorage.setItem(key, JSON.parse(blob));
window.location.reload();
};
// <input type="file" id="input" onChange={(e) => importData("new-tag", e)} />
export const importData = async (key, e) => {
const blob = e.target.files[0];
if (blob && blob.text) {
blob.text().then((text) => saveAndReload(key, text));
} else if (blob) {
const text = await new Response(blob).text();
saveAndReload(key, text);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment