Last active
January 10, 2025 10:02
-
-
Save clucle/8f6bb67f1f38ac5bb595f43a4efb8e0c to your computer and use it in GitHub Desktop.
pure js save text and json object to file
This file contains 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
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(); | |
} |
Thanks, I have been looking for something like this for ages
Had a URL.createObjectURL is not a function error.
So prefixing it as: window.URL.createObjectURL(file); worked.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice, this is very helpful !