-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?

3
  • @KenWhite that question is specifically about Windows platforms and reading from local disk. This question is not tagged either of those. Commented Dec 28, 2012 at 20:41
  • @tkone: No problem. Use this one as the duplicate instead. Or this one. Or this one. Do you want me to go on? :-) There are at least three more just in the related list alone, without bothering to search. Commented Dec 28, 2012 at 20:47
  • it is a possible duplicate question Commented Dec 28, 2012 at 21:52

2 Answers 2

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.

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

2 Comments

The file is in my local computer. I want to open it, read its contents, and finally edit its contents and save it in the same location on my local computer. Is it possible?
No. JavaScript cannot write to your local file system.
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).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.