Import a text file using Javascript

I am currently working on an application that processes a fairly large amount of data. I currently hardcoded these values ​​in Javascript iself (defining global arrays), but this method does not seem to be robust.

Is there a way to use Javascript to parse a .txt file located in the same directory on the server? I know that this question was probably asked earlier, but I found answers only to access system local text files.

+4
source share
2 answers

Use AJAX. I suggest encoding the file in JSON format rather than plain text. If you use jQuery, you can use $.getJSON('filename.txt') to read the file and parse it into a Javascript object in one operation.

+2
source

Here is a proprietary JavaScript solution without libraries.

http://caniuse.com/xhr2

As asynchronously, you need to create 2 functions

one to read and another to show / change or something else

 function read(textFile){ var xhr=new XMLHttpRequest; xhr.open('GET',textFile); xhr.onload=show; xhr.send() } function show(){ var pre=document.createElement('pre'); pre.textContent=this.response; document.body.appendChild(pre) } read('text.txt'); 

If you work a lot with external files, I suggest also take a look at the new javascript classes new FileReader() and window.requestFileSystem()

where new FileReader() now has a bit more support, also on mobile devices

and from what I know window.requestFileSystem() is almost not supported .. but you can handle files that are large gb large .. using Chrome.

+3
source

Source: https://habr.com/ru/post/1498261/


All Articles