12

What code should I use to display the contents of a plain-text .txt file in JavaScript? I want the text to scroll on screen in the active window.

Thanks in advance!

3
  • As Patrick asked; the most important question is: Where is the text file? Commented Sep 21, 2013 at 13:21
  • Sorry for not including that, the file is server-side. Commented Sep 21, 2013 at 15:50
  • Similar: stackoverflow.com/questions/25535125/display-text-file-in-htm Commented May 3, 2015 at 19:39

2 Answers 2

14

To get the text to display with new lines etc, use a <pre> or a <textarea>, i.e.

<pre id="contents"></pre>

Next is, where is the plain text file?

From a Server

Use XMLHttpRequest

function populatePre(url) {
    var xhr = new XMLHttpRequest();
    xhr.onload = function () {
        document.getElementById('contents').textContent = this.responseText;
    };
    xhr.open('GET', url);
    xhr.send();
}
populatePre('path/to/file.txt');

From the local machine

Make the user select the file using an <input type="file" />

<input type="file" id="filechoice" />

Then when the user selects a file, use FileReader to populate the <pre>

document
    .getElementById('filechoice')
    .addEventListener(
        'change',
        function () {
            var fr = new FileReader();
            fr.onload = function () {
                document.getElementById('contents').textContent = this.result;
            };
            fr.readAsText(this.files[0]);
        }
    );
Sign up to request clarification or add additional context in comments.

Comments

2

We can use below code for this purpose:

<iframe src="http://dev.imaginestudios.cu.cc/test.txt"></iframe> 

Example

Ref: Display text file in HTML

1 Comment

I don't think that's what it was asked in the question. It was said “display the contents of a plain-text .txt file in JavaScript”.

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.