How to read a local text file?

前端 未结 20 2308
北恋
北恋 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:07

    Jon Perryman,

    Yes js can read local files (see FileReader()) but not automatically: the user has to pass the file or a list of files to the script with an html <input type=file>.

    Then with js it is possible to process (example view) the file or the list of files, some of their properties and the file or files content.

    What js cannot do for security reasons is to access automatically (without the user input) to the filesystem of his computer.

    To allow js to acccess to the local fs automatically is needed to create not an html file with js inside it but an hta document.

    An hta file can contain js or vbs inside it.

    But the hta executable will work on windows systems only.

    This is standard browser behavior.

    Also google chrome worked at the fs api, more infos here: http://www.html5rocks.com/en/tutorials/file/filesystem/

    0 讨论(0)
  • 2020-11-21 06:07

    Get local file data in js(data.js) load:

    function loadMyFile(){
        console.log("ut:"+unixTimeSec());
        loadScript("data.js?"+unixTimeSec(), loadParse);
    }
    function loadParse(){
        var mA_=mSdata.split("\n");
        console.log(mA_.length);
    }
    function loadScript(url, callback){
    
        var script = document.createElement("script")
        script.type = "text/javascript";
    
        if (script.readyState){  //IE
            script.onreadystatechange = function(){
                if (script.readyState == "loaded" ||
                        script.readyState == "complete"){
                    script.onreadystatechange = null;
                    callback();
                }
            };
        } else {  //Others
            script.onload = function(){
                callback();
            };
        }
    
        script.src = url;
        document.getElementsByTagName("head")[0].appendChild(script);
    }
    function hereDoc(f) {
      return f.toString().
          replace(/^[^\/]+\/\*![^\r\n]*[\r\n]*/, "").
          replace(/[\r\n][^\r\n]*\*\/[^\/]+$/, "");
    }
    function unixTimeSec(){
        return Math.round( (new Date()).getTime()/1000);
    }
    

    file of data.js like:

    var mSdata = hereDoc(function() {/*!
    17,399
    1237,399
    BLAHBLAH
    BLAHBLAH
    155,82
    194,376
    */});
    

    dynamic unixTime queryString prevents cached.

    AJ works in web http://.

    0 讨论(0)
提交回复
热议问题