0

i just want to read a local text file and assign it to a variable. I don't see why this code doesn't work. I have already looked almost in any response on stackoverflow since yesterday and that's the only synchronous way i have found.

Anybody sees the problem ?

function readTextFile(file){

var request = new XMLHttpRequest();

request.open('GET', file);
request.onreadystatechange = function(){
console.log(request);
console.log(request.responseText);
return request.responseText;
}
}
keremistan
  • 414
  • 5
  • 17
  • Where are you sending the request? A `return` inside `onreadystatechange` has no meaning. This isn’t synchronous. Why do you want to make it synchronous in the first place? – Sebastian Simon Jul 12 '18 at 16:23
  • I have tried the async, but 'everytime' i got the error undefined, since the execution continues, but the file hasn't been read yet. – keremistan Jul 12 '18 at 16:24
  • I send it nowhere, just trying simply read a local text file – keremistan Jul 12 '18 at 16:25
  • Please don’t make it synchronous. Read [How do I return the response from an asynchronous call?](https://stackoverflow.com/q/14220321/4642212). – Sebastian Simon Jul 12 '18 at 16:25
  • 1
    If you don’t `send` the request, then nothing will happen. Please read the docs on [`XMLHttpRequest`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest), or even better: use the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) instead. – Sebastian Simon Jul 12 '18 at 16:27
  • isn't that supposed to be working with fetch? fetch('pathTo/some.csv') .then(re => // console.log("in the fetch " + re.text()) data_array = re.text() ) – keremistan Jul 12 '18 at 16:50
  • it's still undefined, eventhough it's in the then part – keremistan Jul 12 '18 at 16:50
  • 1
    You need to return `re.text()` before you can work with the data: `fetch("pathTo/some.csv").then((re) => re.text()).then((data) => console.log(data))`. It’s not possible to use the data in a global variable outside of an asynchronous call. – Sebastian Simon Jul 12 '18 at 16:56
  • *"I don't see why this code doesn't work"* well that call is not synchronous and you can not return from onreadystate so seems like there are a bunch of reasons why it will not work. – epascarello Jul 12 '18 at 17:28

0 Answers0