How do I load the contents of a text file into a javascript variable?

后端 未结 9 801
南笙
南笙 2020-11-22 07:22

I have a text file in the root of my web app http://localhost/foo.txt and I\'d like to load it into a variable in javascript.. in groovy I would do this:

         


        
9条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 08:00

    Update 2020: Using Fetch with async/await

    const response = await fetch('http://localhost/foo.txt');
    const data = await response.text();
    console.log(data);
    

    Note that await can only be used in an async function. A longer example might be

    async function loadFileAndPrintToConsole(url) {
      try {
        const response = await fetch(url);
        const data = await response.text();
        console.log(data);
      } catch (err) {
        console.error(err);
      }
    }
    
    loadFileAndPrintToConsole('https://threejsfundamentals.org/LICENSE');

提交回复
热议问题