问题
Let's say I have a data file named "data.json" which contains some JSON or it can be blank. I created a function that packs my JSON string inside a variable, so if I do,
var myJSONVar = myJSONString;
console.log(myJSONVar);
I will print,
[{ "my":"JSON" }]
How can I dump the content of myJSONVar to the "data.json" file with Javascript, without the need to use a server side language or external JS library? Is this totally impossible?
回答1:
i don't think it's very impossible, unless you are talking about legacy machines, in which case you'll need a server echo of some sort.
in current versions of all three major browsers you can download a file with a custom name from a string with JS:
<script>
//from: http://danml.com/js/download.js
function download(strData, strFileName, strMimeType) {
var D = document,
A = arguments,
a = D.createElement("a"),
d = A[0],
n = A[1],
t = A[2] || "text/plain";
//build download link:
a.href = "data:" + strMimeType + "," + escape(strData);
if (window.MSBlobBuilder) {
var bb = new MSBlobBuilder();
bb.append(strData);
return navigator.msSaveBlob(bb, strFileName);
} /* end if(window.MSBlobBuilder) */
if ('download' in a) {
a.setAttribute("download", n);
a.innerHTML = "downloading...";
D.body.appendChild(a);
setTimeout(function() {
var e = D.createEvent("MouseEvents");
e.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(e);
D.body.removeChild(a);
}, 66);
return true;
} /* end if('download' in a) */
; //end if a[download]?
//do iframe dataURL download:
var f = D.createElement("iframe");
D.body.appendChild(f);
f.src = "data:" + (A[2] ? A[2] : "application/octet-stream") + (window.btoa ? ";base64" : "") + "," + (window.btoa ? window.btoa : escape)(strData);
setTimeout(function() {
D.body.removeChild(f);
}, 333);
return true;
} /* end download() */
var myJSONVar = [{ "my":"JSON" }];
download( JSON.stringify(myJSONVar, null, "\t"), "data.json", "text/plain");
</script>
来源:https://stackoverflow.com/questions/17518801/how-to-append-json-to-already-existing-file-with-javascript