Reading a local text file in JavaScript

元气小坏坏 提交于 2019-12-13 16:49:45

问题


I just started learning JavaScript and I have a small problem. I have a text file with some text in it. I can read the content of the text file in browser (I mean in .hta) but the text appears as a single line. I want to add line breaks to each line. How do I do that?

Text file content:
I want to live where soul meets body
And let the sun wrap its arms around me
...

JS:

var fso = new ActiveXObject("Scripting.FileSystemObject");
var txtFile = fso.OpenTextFile("C:\\myJS\\test.txt", 1, false, 0);
var fText = txtFile.Read(1000);
document.write(fText);
txtFile.Close();
fso = null;

The output:
I want to live where soul meets body And let the sun wrap its arms around me ...

Any advice, suggestion is appreciated.


回答1:


This happens because HTML doesn't recognize linebreaks in the text file. You need to add some HTML to your output. Something like this:

function readFile (path) {
    var fso = new ActiveXObject('Scripting.FileSystemObject'),
        iStream=fso.OpenTextFile(path, 1, false);
    while(!iStream.AtEndOfStream) {
        document.body.innerHTML += iStream.ReadLine() + '<br/>';
    }        
    iStream.Close();
}

This function reads the whole file. If you want to read exactly 1000 lines, you can use a for loop, but you'll need to check that the file is not shorter than 1000 lines by using AtEndOfStream property.

Just take care of this function is invoked within bodytag, or in a window.onload handler. Notice, that my code uses DOM manipulation instead of document.write().



来源:https://stackoverflow.com/questions/15589700/reading-a-local-text-file-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!