Andrew Andrew - 3 months ago 16
Javascript Question

How can i read txt file line by line

I want to read txt file line by line, right now it's showing
everything that i have in my file, i want to pass each new line to variable ,how can i do it?

var file = "file:///C:/Users/Viktor/Desktop/test.txt";

function readTextFile(file,line) {

var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function () {
if(rawFile.readyState === 4) {
if(rawFile.status === 200 || rawFile.status === 0) {
var allText = rawFile.responseText;

}
}
};
rawFile.send(null);
}

readTextFile(file);

Answer

You can split the string on the new lines.

var allText = rawFile.responseText,
    lines = allText.split(/\n/g);  //.split("\n")
console.log(lines.length);