Whilst for the most part one should always try to make downloads be a server-handled thing, sometimes it's faster/easier to generate data in JavaScript... but how do you take a JavaScript variable and make a download out of it without spitting it back to the server?
Well, here's how:
function fileDownload(filename, content, mimeType) {
var a = document.createElement('a');
a.download = filename;
a.href = 'data:' + (
mimeType || 'text/plain'
) + ';charset=utf-8,' + encodeURIComponent(content);
a.style.display = 'none';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
} // _.fileDownload
We make an anchor element, we set the download attribute to our desired filename, then in the href we set data:text/plain (or whatever mime-type you want) with the charset followed by a comma, then a URI encoded version of our data. This anchor when clicked on will magically turn that data: into a download with the DL attribute as the filename.
From there we just make sure it's display:none, append it to the body, trigger its click even, then remove/delete it.
so:
fileDownload('test.txt', 'This is a test');
Will trigger a browser download "test.txt" which contains "this is a test". Easy-peasy lemon squeezy.