I want to write data to a file and open a file dialog for the user to select a location to save the file. Ideally, it should work across all browsers, especially Chrome. What should I include in the saveFile
function to achieve this?
If you’re looking for the simplest and most compatible way to implement javascript save file
, I’d say go with the good old Blob method combined with an <a>
tag. Here’s a quick snippet:
function saveFile(data, filename) {
const blob = new Blob([data], { type: 'text/plain' });
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = filename;
a.click();
}
Why this works:
- No external library required
- Triggers the browser’s download flow
- Compatible with Chrome, Firefox, Edge, and Safari
It’s my go-to for quick and reliable downloads on the client side.
@babitakumari’s method is rock-solid and highly compatible. But if you’re working with Chromium-based browsers and want tighter control, especially over where the user saves the file, the File System Access API adds some polish to the javascript save file
story:
async function saveFile(data) {
const handle = await window.showSaveFilePicker({
suggestedName: 'data.txt',
types: [{ accept: { 'text/plain': ['.txt'] } }]
});
const writable = await handle.createWritable();
await writable.write(data);
await writable.close();
}
Why I like it:
- Opens the native file picker
- Gives the user full control over the save location
- Clean and modern (but yes, limited to Chrome and Edge)
So if your audience is mostly on Chromium browsers, this can feel like a desktop app experience using just javascript save file
functionality."
Both of you covered great options! I’d just add—if your needs are ultra-lightweight and you’re dealing with small snippets of data, you can go even simpler using a data:
URI for javascript save file
.
Sure! Here’s your JavaScript code rewritten in a paragraph format:
To implement a simple javascript save file
functionality, you can create a data URI by concatenating a plain text MIME type with the user-provided data, properly encoded using encodeURIComponent()
. Next, dynamically generate an <a>
(anchor) element and assign this data URI to its href
attribute. Set the download
attribute of the anchor to the desired filename, and finally trigger a click on the anchor element using a.click()
, which prompts the browser to download the file—all without needing external libraries or Blob objects.
What’s nice about this:
- No Blob or async/await required
- 100% client-side and minimal
- Perfect for quick exports or copy-paste utilities
It’s not ideal for big files, but when performance and simplicity matter, this approach makes javascript save file
feel almost instant.