Skip to content

Instantly share code, notes, and snippets.

@karlkori
Created March 18, 2023 13:05
Show Gist options
  • Select an option

  • Save karlkori/227f1fe6874612ca174849f699aeef9e to your computer and use it in GitHub Desktop.

Select an option

Save karlkori/227f1fe6874612ca174849f699aeef9e to your computer and use it in GitHub Desktop.
saveTextAsFile
function saveTextAsFile(textToWrite, fileNameToSaveAs, fileType) {
let textFileAsBlob = new Blob([textToWrite], { type: fileType });
let downloadLink = document.createElement('a');
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = 'Download File';
if (window.webkitURL != null) {
downloadLink.href = window.webkitURL.createObjectURL(
textFileAsBlob
);
} else {
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
downloadLink.style.display = 'none';
document.body.appendChild(downloadLink);
}
downloadLink.click();
}
saveTextAsFile('{"hello": "world"}', 'hello.json', 'application/json');
saveTextAsFile('Hello World!', 'hello.txt', 'text/plain');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment