How Do You Save a File With JavaScript
by Jérémie LITZLER
HTML
<form>
<button>
Download
</button>
</form>
JavaScript
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);
}
const button = document.querySelector('button');
button.addEventListener('click', (event)=>{
event.preventDefault();
downloadFile('demo-file.txt', 'The content was set dynamically using JavScript.');
})