How to read a local text file?

前端 未结 20 2320
北恋
北恋 2020-11-21 05:28

I’m trying to write a simple text file reader by creating a function that takes in the file’s path and converts each line of text into a char array, but it’s not working.

20条回答
  •  旧巷少年郎
    2020-11-21 06:02

    Try creating two functions:

    function getData(){       //this will read file and send information to other function
           var xmlhttp;
    
           if (window.XMLHttpRequest) {
               xmlhttp = new XMLHttpRequest();               
           }           
           else {               
               xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");               
           }
    
           xmlhttp.onreadystatechange = function () {               
               if (xmlhttp.readyState == 4) {                   
                 var lines = xmlhttp.responseText;    //*here we get all lines from text file*
    
                 intoArray(lines);     *//here we call function with parameter "lines*"                   
               }               
           }
    
           xmlhttp.open("GET", "motsim1.txt", true);
           xmlhttp.send();    
    }
    
    function intoArray (lines) {
       // splitting all text data into array "\n" is splitting data from each new line
       //and saving each new line as each element*
    
       var lineArr = lines.split('\n'); 
    
       //just to check if it works output lineArr[index] as below
       document.write(lineArr[2]);         
       document.write(lineArr[3]);
    }
    

提交回复
热议问题