Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
618 views
Welcome To Ask or Share your Answers For Others

1 Answer

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]);
        }
    );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...