Skip to content

Instantly share code, notes, and snippets.

@clucle
Last active May 8, 2024 02:47
Show Gist options
  • Save clucle/8f6bb67f1f38ac5bb595f43a4efb8e0c to your computer and use it in GitHub Desktop.
Save clucle/8f6bb67f1f38ac5bb595f43a4efb8e0c to your computer and use it in GitHub Desktop.
pure js save text and json object to file
function saveTextToFile() {
const saveText = "tmp";
// file setting
const text = saveText;
const name = "sample.json";
const type = "text/plain";
// create file
const a = document.createElement("a");
const file = new Blob([text], { type: type });
a.href = URL.createObjectURL(file);
a.download = name;
document.body.appendChild(a);
a.click();
a.remove();
}
function saveJsonObjToFile() {
const saveObj = { "a": 3 }; // tmp
// file setting
const text = JSON.stringify(saveObj);
const name = "sample.json";
const type = "text/plain";
// create file
const a = document.createElement("a");
const file = new Blob([text], { type: type });
a.href = URL.createObjectURL(file);
a.download = name;
document.body.appendChild(a);
a.click();
a.remove();
}
@Alexie81
Copy link

Nice, this is very helpful !

@stevietelly
Copy link

Thanks, I have been looking for something like this for ages

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment