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!
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?
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');
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]);
        }
    );
                        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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With