How to read a local text file?

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

    How to read a local file?

    By using this you will load a file by loadText() then JS will asynchronously wait until the file is read and loaded after that it will execture readText() function allowing you to continue with your normal JS logic (you can also write a try catch block on the loadText() function in the case any error arises) but for this example I keep it at minimal.

    async function loadText(url) {
        text = await fetch(url);
        //awaits for text.text() prop 
        //and then sends it to readText()
        readText(await text.text());
    }
    
    function readText(text){
        //here you can continue with your JS normal logic
        console.log(text);
    }
    
    loadText('test.txt');
    

提交回复
热议问题