简体   繁体   中英

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.

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.

You can use localStorage as a temporary storage between reads and writes.

Though, you cannot actually read and write to a user's filesystem at will using client side 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. 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.

// 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.

But note that localStorage can only store strings. 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:

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

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:

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.

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.

var file = JSON.stringify(localStorage);

Then send to user as File blob shown above.

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? Or browser javascript?

In either case the structure you should use is js' standard object. Then you can turn it into JSON like this:

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:

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

With browser js, this stackoverflow may help you: Javascript: Create and save file

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.

For security reasons it's not possible to use JavaScript to write to a regular text or similar file on a client's system.

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.

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.

For more information have a look at Read/write to file using jQuery

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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