将 Javascript 对象保存到文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20489454/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 18:36:36  来源:igfitidea点击:

Saving a Javascript object to a file

javascriptfileobjectsave

提问by Shannon Rothe

I need to save a Javascript object to a file, so it can be easily reloaded into a variable, modified and eventually re-saved. Is this feasible in Javascript and if so what's the best way to approach it. For example if I have:

我需要将 Javascript 对象保存到文件中,以便可以轻松地将其重新加载到变量中,进行修改并最终重新保存。这在 Javascript 中是否可行,如果是,最好的方法是什么。例如,如果我有:

o = {"test": 2};

How can I save it to a file, load, modify and save it? Exactly like picklein Python.

如何将其保存到文件、加载、修改和保存?就像pickle在 Python 中一样。

Thanks.

谢谢。

回答by Lenny

If you literally mean a file this is not possible client-side. However, if it's just the data you want to store and recall you can use a cookie if it's small. http://www.sitepoint.com/how-to-deal-with-cookies-in-javascript/

如果您的字面意思是文件,则这在客户端是不可能的。但是,如果它只是您想要存储和调用的数据,那么您可以使用 cookie(如果它很小)。 http://www.sitepoint.com/how-to-deal-with-cookies-in-javascript/

If it's larger you have to use HTML5 LocalStorage. However, this will only work on newer browsers.

如果它更大,则必须使用 HTML5 LocalStorage。但是,这仅适用于较新的浏览器。

You could do this to make a visit counter:

你可以这样做来制作一个访问计数器:

//try to load the data
var o = localStorage.getItem("mydata");
//if the data is empty set the data
if(!o) o = {"test": 0};
//increment the test value inside of o by one each time
o.test++;
//save the data to local storage
localStorage.setItem("mydata", JSON.stringify(o));

http://diveintohtml5.info/storage.html

http://diveintohtml5.info/storage.html

Again, this will ONLY work on modern browsers like Chrome.

同样,这仅适用于 Chrome 等现代浏览器。

The traditional method would be to send it via AJAX to a server side script written in PHP, Python, Ruby, Java, etc...

传统的方法是通过 AJAX 将其发送到用 PHP、Python、Ruby、Java 等编写的服务器端脚本......

回答by CodingIntrigue

Despite all the answers to the contrary, this is indeed possible. However it is limited by browser support. You can use the new FileSystem APIsin the latest versions of Chrome, etc:

尽管所有的答案都与此相反,但这确实是可能的。但是,它受浏览器支持的限制。您可以在最新版本的 Chrome 等中使用新的FileSystem API

window.requestFileSystem  = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(window.PERSISTENT, 1024, function(fs) {
    fs.root.getFile('mystorage.txt', {create: true, exclusive: true}, function(file) {
        file.createWriter(function(writer) {
            var blob = new Blob(["putdatahere"], {type: 'text/plain'});
            writer.write(blob);
        });
    });
}, function() {
    console.log("Could not access file system");
});

Since you only want the files for your own uses, this sandboxed approach will work. There are a few more hoops you need to jump through (requesting a quota, creating a Blobobject) but those are covered by the linked article and will all depend on your requirements.

由于您只需要这些文件供您自己使用,因此这种沙盒方法将有效。您还需要跳过一些障碍(请求配额、创建Blob对象),但这些都包含在链接的文章中,并且都取决于您的要求。

回答by Yair Levy

You can save a file using the "download" attribute on a element. This is how it is done programmaticaly:

您可以使用元素上的“下载”属性保存文件。这是以编程方式完成的方式:

function saveJSON() {
   let data = "Whatever it is you want to save";
   let bl = new Blob([data], {
      type: "text/html"
   });
   let a = document.createElement("a");
   a.href = URL.createObjectURL(bl);
   a.download = "data.json";
   a.hidden = true;
   document.body.appendChild(a);
   a.innerHTML =
      "someinnerhtml";
   a.click();
}