Reading a local text file in JavaScript
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 body
tag, or in a window.onload
handler. Notice, that my code uses DOM manipulation instead of document.write()
.
![akinuri](https://i.stack.imgur.com/wzm22.png?s=256&g=1)
akinuri
An amateur/hobbyist coder and a very curious person. #SOreadytohelp
Updated on December 05, 2020Comments
-
akinuri over 3 years
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.
-
akinuri over 11 yearsHmm. Its either I'm doing something wrong or this doesn't work =\
-
Teemu over 11 years@akinuri OOPS, I'm sorry, I used a wrong property in the loop condition, I've corrected the code.
-
akinuri over 11 yearsIt still doesn't work. It doesn't print anything. Can you try and see if it prints anything? Forget line breaks, I don't even know if its going to print the text. And it seems it doesn't.
-
Teemu over 11 yearsHmm... It seems I'd better go to sleep... Now the code is OK, just corrected the
ActiveX
call. I've also tested the code, and it works now.