0

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);
Rahul Patel
  • 5,248
  • 2
  • 14
  • 26
Andrew
  • 1,507
  • 1
  • 22
  • 42

1 Answers1

1

You can split the string on the new lines.

var allText = rawFile.responseText,
    lines = allText.split(/\n/g);  //.split("\n")
console.log(lines.length);
epascarello
  • 204,599
  • 20
  • 195
  • 236
  • Thanks! and as well is it possible to delete line from txt file? – Andrew Aug 31 '16 at 16:34
  • JavaScript (in the browser) has no way of updating that file directly. You can do something like http://stackoverflow.com/questions/18690450/how-to-generate-and-prompt-to-save-a-file-from-content-in-the-client-browser – epascarello Aug 31 '16 at 16:35