开发者

How can you read a file line by line in JavaScript?

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 everythi开发者_开发问答ng 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)


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


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..


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜