0

This code is used to read a .txt file in Javascript:

function readFile(fileName) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
        document.getElementById("demo").innerHTML = this.responseText;
        console.log(his.responseText);
        return this.responseText
    }
};
xhttp.open("GET", fileName, true);
xhttp.send();}

This code print out the file contents into the console. I want to use the file content for further processing. When I try to read the contents using these two lines inside JavaScript:

contents = readFile("data.txt");
console.log(contents);

the console displays: undefined. How can I fix that?

  • 2
    Does this answer your question? [How to read text file in JavaScript](https://stackoverflow.com/questions/13709482/how-to-read-text-file-in-javascript) – Vendetta Feb 21 '20 at 17:56

1 Answers1

0

You can't use the asynchronous result in a synchronous way, instead you can call another function when the promise resolves and do what want there.

function readFile(fileName) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function () {
      if (this.readyState == 4 && this.status == 200) {
          document.getElementById("demo").innerHTML = this.responseText;
          console.log(his.responseText);
          doSomething(this.responseText);   //call the function when the promise resolves and do what you want there
      }
  };
  xhttp.open("GET", fileName, true);
  xhttp.send();
}

function doSomething(text) {
  //do what you want to do with the text here. 'text' here is the responseText
  console.log(text);

}
Addis
  • 2,480
  • 2
  • 13
  • 21
  • I have replaced:contents = readFile("data.txt"); console.log(contents); by your answer. An error occurred that it cannot read property 'then' of undefined. – Zain Al-Ain Feb 21 '20 at 18:23
  • It's OK now but I want to get the result of `doSomething(this.responseText)` out of `readFile(fileName)` function for further processing. How can I do that? – Zain Al-Ain Feb 21 '20 at 19:06
  • you will find the result as the argument of `doSomething` function, which is `text`. So consider text as the returned value and do the "further processing" inside of the function `doSomething`. – Addis Feb 21 '20 at 19:09
  • I made my process inside `doSomething` to get a value. I want this value to be returned outside these functions to be used in my main JS code. This is my point. Thanks for the help. – Zain Al-Ain Feb 21 '20 at 19:21
  • you can't get the result outside of a function, that's not possible! – Addis Feb 21 '20 at 19:30