Create and download text files using JavaScript
There are a couple of projects of mine where I needed to create and download text/JSON files using JavaScript. For instance, in LinkSnatch, I needed a way to export the bookmarks as a JSON file or in my Notepad app, I needed a way to export the notes as a text file.
I use the following function to create and download various types of files using JavaScript.
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();
}
The function is pretty simple. It takes the text to write, the file name to save, and the file type as the arguments. Then, it creates a new Blob
object with the given text and file type. After that, it creates a new a
element and sets the download
attribute to the given file name.
Then, it checks if the webkitURL
object is available in the window
object. If it is, it uses the createObjectURL()
method to create a URL for the Blob
object. Otherwise, it uses the URL.createObjectURL()
method to create a URL for the Blob
object.
Then, it sets the href
attribute of the a
element to the URL created above. After that, it appends the a
element to the body
element and clicks it.
So, if you want to create and download a text file using JavaScript, you can use the above function. For instance, if you want to create and download a text file with the name hello.txt
and the content Hello World!
, you can do it like so.
saveTextAsFile('Hello World!', 'hello.txt', 'text/plain');
Similarly, if you want to create and download a JSON file with the name hello.json
and the content {"hello": "world"}
, you can do it like so.
saveTextAsFile('{"hello": "world"}', 'hello.json', 'application/json');
I created a CodePen demo for the same. You can check it out here.
See the Pen Animated gradient effect using CSS by Amit Merchant (@amit_merchant) on CodePen.
Like this article?
Buy me a coffee👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.