How to read a local text file?

前端 未结 20 2248
北恋
北恋 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 05:52

    function readTextFile(file) {
        var rawFile = new XMLHttpRequest(); // XMLHttpRequest (often abbreviated as XHR) is a browser object accessible in JavaScript that provides data in XML, JSON, but also HTML format, or even a simple text using HTTP requests.
        rawFile.open("GET", file, false); // open with method GET the file with the link file ,  false (synchronous)
        rawFile.onreadystatechange = function ()
        {
            if(rawFile.readyState === 4) // readyState = 4: request finished and response is ready
            {
                if(rawFile.status === 200) // status 200: "OK"
                {
                    var allText = rawFile.responseText; //  Returns the response data as a string
                    console.log(allText); // display text on the console
                }
            }
        }
        rawFile.send(null); //Sends the request to the server Used for GET requests with param null
    }
    
    readTextFile("text.txt"); //<= Call function ===== don't need "file:///..." just the path 
    

    - read file text from javascript
    - Console log text from file using javascript
    - Google chrome and mozilla firefox

    in my case i have this structure of files :

    the console.log result :

提交回复
热议问题