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

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

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