简体   繁体   English

我如何逐行读取txt文件

[英]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? 我想逐行阅读txt文件,现在它显示了我文件中的所有内容,我想将每一行都传递给变量,该怎么办?

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);

You can split the string on the new lines. 您可以在新行上分割字符串。

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

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

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