4

I am currently working on an application that handles a fairly large amount of data. Currently, I've hard-coded those values into the Javascript iself (defining global arrays), but this method does not seem sustainable.

Is there a way to use Javascript to parse a .txt file located in the same directory on the server? I know this question has probably been asked before, but I've only found answers pertaining to accessing system-local text files.

1
  • Yeah it is possible, what have you tried, what are the answers you have found? Commented Aug 21, 2013 at 19:41

2 Answers 2

3

Here is native javascript solution without libraries.

http://caniuse.com/xhr2

As it's async you have to create 2 functions

one to read and another one to show/modify or whatever

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 alot with external files i suggest also to take a look at the new javascript classes new FileReader() and window.requestFileSystem()

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

and from what i know window.requestFileSystem() has almost no support.. but you can handle files that are various gb large.. using Chrome.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.