Search code examples
javascriptfiletextfetch

how to save local file content using fetch in javascript


I have a text.txt file and I want to save its content in a variable. My problem is that I can log the text but I can't store it in a var

let fileText;
fetch("./text.txt")
    .then(response => response.text())
    .then(text => fileText = text);
    console.log(fileText);  // undefined


Solution

  • The console.log will be executed before the fetch promise resolved.

    If you want line-by-line syntax execution you can use async/await.

    let fileText;
    
    (async () => {
    const response = await fetch("./text.txt")
    const text = await response.text()
    fileText = text;
    console.log(fileText);
    })()