Is possible to save JavaScript variable as file? [closed]

is there any way to store JavaScript variable into file (eg. TXT, XML...), which can be downloaded from browser to PC?

Thanks for any advice.

Answers:

Answer

Yes it is, you could do something like this in HTML5, using the download attribute

var textToSave = 'this is a test';

var hiddenElement = document.createElement('a');

hiddenElement.href = 'data:attachment/text,' + encodeURI(textToSave);
hiddenElement.target = '_blank';
hiddenElement.download = 'myFile.txt';
hiddenElement.click();

FIDDLE

Answer

You can use a data: URI like in adeneo's answer, but another way is to use an HTML5 Blob and createObjectURL (similarly using the download attribute to create a download link).

The benefit of using createObjectURL is that there are severe size limits to data URIs in most browsers.

Example code taken from linked article:

var typedArray = GetTheTypedArraySomehow();
var blob = new Blob([typedArray], {type: 'application/octet-binary'});
    // pass a useful mime type here
var url = URL.createObjectURL(blob);
// url will be something like: blob:d3958f5c-0777-0845-9dcf-2cb28783acaf
// now you can use the url in any context that regular URLs can be used
// in, for example img.src, etc.
Answer

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.