To store a javascript variable, I suggest you to use libraries of data storage just like this one. where you can set a variable, get it , remove it ...
$.setData("key","value");
$.getData("key");
$.removeData("key");
but to store it on a file and make downloadable you have to pass by the server unless you use a javascript trick to download a file which doesn't exist, you just declare these functions
var Download =
{
click : function(node) {
var ev = document.createEvent("MouseEvents");
ev.initMouseEvent("click", true, false, self, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
return node.dispatchEvent(ev);
},
encode : function(data) {
return 'data:application/octet-stream;base64,' + btoa( data );
},
link : function(data, name){
var a = document.createElement('a');
a.download = name || self.location.pathname.slice(self.location.pathname.lastIndexOf('/')+1);
a.href = data || self.location.href;
return a;
}
};
Download.save = function(data, name)
{
this.click(
this.link(
this.encode( data ),
name
)
);
};
and when you want to download a file, you do this
Download.save("data to be on a file","FileName.txt");
Finally, you need to combine the datastorage and the filedownload solution to get the result you're asking for