简体   繁体   English

在JavaScript中读取本地文本文件

[英]Reading a local text file in JavaScript

I just started learning JavaScript and I have a small problem. 我刚刚开始学习JavaScript,但遇到了一个小问题。 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. 我可以在浏览器中读取文本文件的内容(我的意思是.hta),但文本显示为一行。 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: 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. 任何意见,建议表示赞赏。

This happens because HTML doesn't recognize linebreaks in the text file. 发生这种情况是因为HTML无法识别文本文件中的换行符。 You need to add some HTML to your output. 您需要在输出中添加一些HTML。 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. 如果您想精确读取1000行,可以使用for循环,但是您需要使用AtEndOfStream属性检查文件是否不少于1000行。

Just take care of this function is invoked within body tag, or in a window.onload handler. 只需注意此函数是在body标签内或在window.onload处理程序中调用的即可。 Notice, that my code uses DOM manipulation instead of document.write() . 注意,我的代码使用DOM操纵而不是document.write()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM