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

前端 未结 4 484
眼角桃花
眼角桃花 2020-12-03 15:38

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

相关标签:
4条回答
  • 2020-12-03 16:15

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

    0 讨论(0)
  • 2020-12-03 16:19

    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);
    
    0 讨论(0)
  • 2020-12-03 16:20

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

    0 讨论(0)
  • 2020-12-03 16:31

    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');
    
    0 讨论(0)
提交回复
热议问题