简体   繁体   English

用javascript读取/写入文件

[英]Reading/Writing to a file in javascript

I want to read and write to a file in a specific way. 我想以特定方式读取和写入文件。

An example file could be: 示例文件可以是:

name1:100

name2:400

name3:7865786

...etc etc

What would be the best way to read this data in and store in, and eventually write it out? 将数据读入并存储并最终写出的最佳方法是什么? I don't know which type of data structure to use? 我不知道要使用哪种类型的数据结构? I'm still fairly new to javascript. 我对javascript还是很陌生。

I want to be able to determine if any key,values are matching. 我希望能够确定是否有任何键值匹配。 For example, if I were to add to the file, I could see that name1 is already in the file, and I just edit the value instead of adding a duplicate. 例如,如果要添加到文件中,则可以看到name1已存在于文件中,而我只是编辑该值而不是添加重复项。

You can use localStorage as a temporary storage between reads and writes. 您可以将localStorage用作读取和写入之间的临时存储。

Though, you cannot actually read and write to a user's filesystem at will using client side JavaScript. 但是,您实际上无法使用客户端JavaScript随意读写用户的文件系统。 You can however request the user to select a file to read the same way you can request the user to save the data you push, as a file. 但是,您可以请求用户选择一个文件来读取,就像请求用户将您推送的数据另存为文件一样。

localStorage allow you to store the data as key-value pairs and it's easy to check if an item exists or not. localStorage允许您将数据存储为键值对,并且很容易检查某项是否存在。 Optionally simply use a literal object which basically can do the same but only exists in memory. 可以选择仅使用文字对象,该对象基本上可以执行相同操作,但仅存在于内存中。 localStorage can be saved between sessions and navigation between pages. 可以在会话之间和页面之间的导航之间保存localStorage

// set some data
localStorage.setItem("key", "value");

// get some data
var data = localStorage.getItem("key");

// check if key exists, set if not (though, you can simply override the key as well)
if (!localStorage.getItem("key")) localStorage.setItem("key", "value");

The method getItem will always return null if the key doesn't exist. 如果键不存在,则方法getItem将始终返回null

But note that localStorage can only store strings. 但请注意, localStorage只能存储字符串。 For binary data and/or large sizes, look into Indexed DB instead. 对于二进制数据和/或大容量数据,请查看索引数据库

To read a file you have to request the user to select one (or several): 要读取文件,您必须请求用户选择一个(或多个):

HTML: HTML:

<label>Select a file: <input type=file id=selFile></label>

JavaScript 的JavaScript

document.getElementById("selFile").onchange = function() {
  var fileReader = new FileReader();
  fileReader.onload = function() {
    var txt = this.result;
    // now we have the selected file as text.
  };
  fileReader.readAsText(this.files[0]);
};

To save a file you can use File objects this way: 要保存文件,您可以通过以下方式使用File对象:

var file = new File([txt], "myFilename.txt", {type: "application/octet-stream"});
var blobUrl = (URL || webkitURL).createObjectURL(file);
window.location = blobUrl;

The reason for using octet-stream is to "force" the browser to show a save as dialog instead of it trying to show the file in the tab, which would happen if we used text/plain as type. 使用八位字节流的原因是“强制”浏览器显示“另存为”对话框,而不是尝试在选项卡中显示文件,如果我们使用text / plain作为类型,则会发生这种情况。

So, how do we get the data between these stages. 因此,我们如何获得这些阶段之间的数据。 Assuming you're using key/value approach and text only you can use JSON objects. 假设您仅使用键/值方法和文本,则可以使用JSON对象。

var file = JSON.stringify(localStorage);

Then send to user as File blob shown above. 然后以上面显示的文件blob的形式发送给用户。

To read you will have to either manually parse the file format if the data exists in a particular format, or if the data is the same as you save out you can read in the file as shown above, then convert it from string to an object: 要读取,您将必须手动解析文件格式(如果数据以特定格式存在),或者如果数据与保存的相同,则可以如上所示读取文件,然后将其从字符串转换为对象:

var data = JSON.parse(txt);        // continue in the function block above
Object.assign(localStorage, data); // merge data from object with localStorage

Note that you may have to delete items from the storage first. 请注意,您可能必须先从存储中删除项目。 There is also the chance other data have been stored there so these are cases that needs to be considered, but this is the basis of one approach. 也有可能其他数据已存储在此处,因此需要考虑这些情况,但这是一种方法的基础。

Example

 // due to security reasons, localStorage can't be used in stacksnippet, // so we'll use an object instead var test = {"myKey": "Hello there!"}; // localStorage.setItem("myKey", "Hello there!"); document.getElementById("selFile").onchange = function() { var fileReader = new FileReader(); fileReader.onload = function() { var o = JSON.parse(this.result); //Object.assign(localStorage, o); // use this with localStorage alert("done, myKey=" + o["myKey"]); // o[] -> localStorage.getItem("myKey") }; fileReader.readAsText(this.files[0]); }; document.querySelector("button").onclick = function() { var json = JSON.stringify(test); // test -> localStorage var file = new File([json], "myFilename.txt", {type: "application/octet-stream"}); var blobUrl = (URL || webkitURL).createObjectURL(file); window.location = blobUrl; } 
 Save first: <button>Save file</button> (<code>"myKey" = "Hello there!"</code>)<br><br> Then read the saved file back in:<br> <label>Select a file: <input type=file id=selFile></label> 

Are you using Nodejs? 您正在使用Nodejs吗? Or browser javascript? 还是浏览器JavaScript?

In either case the structure you should use is js' standard object. 无论哪种情况,您都应该使用js的标准对象作为结构。 Then you can turn it into JSON like this: 然后,您可以将其转换为JSON,如下所示:

var dataJSON = JSON.stringify(yourDataObj)

With Nodejs, you'll want to require the fs module and use one of the writeFile or appendFile functions -- here's sample code: 使用Nodejs,您将需要fs模块并使用writeFileappendFile函数之一-这是示例代码:

const fs = require('fs');
fs.writeFileSync('my/file/path', dataJSON);

With browser js, this stackoverflow may help you: Javascript: Create and save file 使用浏览器js,此stackoverflow可能会帮助您: Javascript:创建并保存文件

I know you want to write to a file, but but consider a database instead so that you don't have to reinvent the wheel. 我知道您想写入文件,但是可以考虑使用数据库,这样您就不必重新发明轮子了。 INSERT ... ON DUPLICATE KEY UPDATE seems like the logical choice for what you're looking to do. INSERT ... ON DUPLICATE KEY UPDATE对于您要执行的操作来说似乎是合乎逻辑的选择。

For security reasons it's not possible to use JavaScript to write to a regular text or similar file on a client's system. 出于安全原因,无法使用JavaScript写入客户端系统上的常规文本或类似文件。

However Asynchronous JavaScript and XML (AJAX) can be used to send an XMLHttpRequest to a file on the server, written in a server-side language like PHP or ASP. 但是,可以使用异步JavaScript和XML(AJAX)将XMLHttpRequest发送到服务器上的文件,该文件以服务器端语言(如PHP或ASP)编写。

The server-side file can then write to other files, or a database on the server. 然后,服务器端文件可以写入其他文件或服务器上的数据库。

Cookies are useful if you just need to save relatively small amounts of data locally on a client's system. 如果您只需要在客户端系统上本地保存相对少量的数据,则Cookie很有用。

For more information have a look at Read/write to file using jQuery 有关更多信息,请参见使用jQuery读取/写入文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM