Is it possible to write data to file using only JavaScript?
To write data to a file in-browser using JavaScript, we can utilize the power of Blob
objects and an <a>
element to trigger the download:
This will create a file named "savedText.txt" with the content "Example text to save" that users can download immediately.
User Experience Enhancement
Prompt for Immediate Download
To automatically trigger the download without waiting for the user to click, we can synchronize with the browser’s frame rendering utilizing window.requestAnimationFrame
:
Handling File Names
The download
attribute suggests our preferred file name for users to organize their newly downloaded files:
Clean Up Object URLs
To avoid memory leaks when generating files, especially multiple files in one session, we need to revoke the object URLs right after the download is initiated:
What about Non-text File Data?
JavaScript is flexible, it can create downloadable binary files, for example, saving a PNG image, with the correct MIME type and data:
Make your Download Handling Funky
Allow User-defined File Names
Enable users to name their files or fall back to a default:
Expedite Downloads with Data URI Scheme
If you opt for direct downloads without creating blobs, there's the data URI scheme:
Older Browsers Need Love Too
Don't ignore users of older browsers. Adapt methods according to the browser's capabilities:
Handling Non-text Binary Data
Make sure to prepare your binary data properly (say, base64 decoded) before feeding it to the Blob monster:
Was this article helpful?