How can you read a file line by line in JavaScript

2019-01-12 00:56发布

问题:

I'm writing a web-app for the iPad that will be loading data from a text file. (A sample data set is around ~400 kb). I have everything set up except the file reading. The way I have set up my code, you pass an object which reads a file line by line.

How can I read a file line by line?

If there is no direct way to read a file line by line, can someone please show me an example of how to read a file into a string object? (so that I can use the split method :P)

回答1:

This could work, if I understood what you want to do:

var txtFile = new XMLHttpRequest();
txtFile.open("GET", "http://website.com/file.txt", true);
txtFile.onreadystatechange = function()
{
  if (txtFile.readyState === 4) {  // document is ready to parse.
    if (txtFile.status === 200) {  // file is found
      allText = txtFile.responseText; 
      lines = txtFile.responseText.split("\n");
    }
  }
}
txtFile.send(null);


回答2:

Mobile Safari doesn't have the File API, so I assume you're talking about reading from a web resource. You can't do that. When you read a resource via ajax, the browser will first read it fully into memory and then pass the entire string to your ajax callback as a string.

In your callback, you can take the string and break it into lines, and wrap that up in an object that has the API that your code wants, but you're still going to have the string in memory all at once..



回答3:

With jQuery:

myObject = {}; //myObject[numberline] = "textEachLine";
$.get('path/myFile.txt', function(myContentFile) {
   var lines = myContentFile.split("\r\n");

   for(var i  in lines){
      //here your code
      //each line is "lines[i]"

      //save in object "myObject": 
      myObject[i] = lines[i]

      //print in console
      console.log("line " + i + " :" + lines[i]);
   }
}, 'text');


回答4:

i dont think thats possible until you use ajax to hit some server side code.