简体   繁体   中英

Trying to load a text file into a <p> tag, why is it not working?

I've been looking at other stackoverflow questions pertaining to this and I do not understand why this snippet of code is not working. Right now I am first just trying to get the text to console log to see if it will work at all. I am following line-by-line other people's code it will just not work for this case, and I am unsure why.

const file = "1.txt";

let reader = new FileReader();

reader.onload = (e) => {
    const file = e.target.result;
    const lines = file.split(/\r\n|\n/);
    console.log(lines.join('\n'));
};

reader.readAsText(file); 

For anyone else having this specific issue I found that the fetch() function was the key to my issue. If you do something like:

fetch('1.txt')
  .then(response => response.text())
  .then(data => {
      // Do something with your data
      console.log(data);
  });

Thank you to all the comments I received it helped me find this solution!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM