0

So what I'm trying to do is get text from a file in the same directory as my html file using JavaScript. I want to store an array inside a text file and change it whenever i want instead of constantly having to go into the code, save it, check if it works etc.

I've tried looking around but couldn't find any clear information, most of what I found is using .readAsBinaryString, etc..

I'm mostly seeing things like this but i can't seem find anything which is actually getting information from a textfile without making the person find the text file directory.

function storearray(newval){
     var file = "file location;"
     var txt = file.txt;

     var array = txt.split("|");
     txt = txt + newval + " | ";

     return array; 
}
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • If I get you right, you want to read a file without user interaction. This is not possible by design. An app running in a browser is always forced to open the file dialog when it needs access to a file. There is no way around due to security policy. –  Apr 06 '21 at 10:02

1 Answers1

0

To read a file from the user's disk you need to use FileReader and the user must explicitly select the file using a file input. (See JavaScript read file without using input).

To read a a file from the website you need to use Ajax (with fetch, XMLHttpRequest or a library that wraps around them like Axios). (See Using fetch from MDN).

If (as it seems here) you want to read data from the website but the website exists only on the user's disk then you still need to use Ajax but will usually run into security restrictions. Some browsers allow you to disable the security protection, but the general solution is to install a web server and load both HTML and the data file using HTTP.

Alternatively, you can store your data in JavaScript (you are generating an array from your text file, you can so that manually or have a build-time script do it) and just load it with a <script> element.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335