A "Do Something Great" sign in the dark

How Do You Save a File With JavaScript?

Sometimes, it’s handy to save some content directly from JavaScript to a physical file. Here is the code!

The Code

It’s simple:

  • Create an anchor (a) element.
  • Append it to the DOM.
  • Simulate a click
  • Remove the element from the DOM
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
function downloadFile(filename, textData, dataType = "text/plain") {
  const node = Object.assign(document.createElement("a"), {
    href: `data:${dataType};charset=utf-8,${encodeURIComponent(textData)}`,
    download: filename,
    style: "display: none",
  });
  document.body.appendChild(node);
  node.click();
  document.body.removeChild(node);
}

The Live Demo

Here is a live demo on jsfiddle.

Follow me

Thanks for reading this article. Make sure to follow me on X, subscribe to my Substack publication and bookmark my blog to read more in the future.

Credit: photo by Clark Tibbs on Unsplash.

License GPLv3 | Terms
Built with Hugo
Theme Stack designed by Jimmy