-2

Possible Duplicate:
Reading a txt file from Javascript

I need to open and read the contents of a txt file using JavaScript. How can I do this?

Community
  • 1
  • 1
MJ_Developer
  • 546
  • 1
  • 3
  • 15
  • @KenWhite that question is specifically about Windows platforms and reading from local disk. This question is not tagged either of those. – tkone Dec 28 '12 at 20:41
  • @tkone: No problem. Use [this one](http://stackoverflow.com/q/7261925/62576) as the duplicate instead. Or [this one](http://stackoverflow.com/questions/8137225/read-txt-file-via-client-javascript?rq=1). Or [this one](http://stackoverflow.com/questions/13238415/how-can-you-read-write-and-create-txt-files-using-javascript?rq=1). Do you want me to go on? :-) There are at least three more just in the related list alone, without bothering to search. – Ken White Dec 28 '12 at 20:47
  • it is a possible duplicate question – Paritosh Dec 28 '12 at 21:52

2 Answers2

2

On a remote server you'd just use an XMLHttpRequest object to retrieve the data and access it.

var request = new XMLHttpRequest();
request.open('GET', URL TO FILE);
request.onreadystatechange(function(){
      if(request.readyState === 4 && request.statusCode === 200){
          console.log(request.responseText);
      }
});
request.send();

That will fail in IE7, 8 and probably 9.

If you're trying to read from local disk, you're going to have a bad time.

tkone
  • 22,092
  • 5
  • 54
  • 78
1

If the text file is in your local file system, you'll have a hard time doing so because of the restrictions of Javascript in accessing one's local file system. If the text file is in a server, you can fetch the contents of the file with a simple XHR (Ajax call).

rodrigo-silveira
  • 12,607
  • 11
  • 69
  • 123