I have a javascript function in which I would like to read an entire text file from my local computer. And store the entire file in a javascript variable. Then be able to return this variable to another function. I've researched different sites that said I could use XMLHttpRequest method to do so and I've tried using an absolute file path and relative file path. I just want a new set of eyes on the issue just in case I'm missing something smmall or completely off. The code is below
function setNewTexts()
{
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "textfile.txt", true);
txtFile.onreadystatechange = function()
{
if (txtFile.readyState === 4) { // document is ready to parse.
if (txtFile.status === 200) { // file is found
allText = txtFile.responseText;
lines = txtFile.responseText.split("\n");
}
}
}
txtFile.send(null);
var text = "go go go ";
return textFile;
}
value = setNewTexts();
3 Answers 3
return textFile;
textFile is not defined. Everywhere else, you use the variable txtFile. Possibly a typo here. This could be your problem.
Comments
XMLHttpRequest cannot load file:///home/username/txtfile.txt. Cross origin requests are only supported for HTTP.
This means that your browser, for security reasons, will not allow you to read files from outside your domain. In your case, file:///, you don't have a domain. Some older browsers allowed this, but that was the wild west of the web. You will need to run a server locally in order to do what you're trying to do.
Comments
If you would test your script on local computer (i.e. html file where script is running and textfile.txt are local) then you should remove the if(txtFile.status === 200) { ... } check as it is not always true in local runs even if file is really there.
And the main point. Since you intentionally made you request async (by passing truein txtFile.open("GET", "textfile.txt", true);) then you should change your function for example like follows:
function setNewTexts(callback) { {
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "textfile.txt", true);
txtFile.onreadystatechange = function() {
if (txtFile.readyState === 4) { // document is ready to parse.
if (txtFile.status === 200) { // file is found
var lines = txtFile.responseText.split("\n");
callback(lines);
}
}
}
txtFile.send(null);
}
And somewhere else where you need the content of the textfile.txt:
var value;
setNewTexts(function (lines) {
value = lines;
});
The point is that since your request is async onreadystatechange handler will be executed after setNewTexts is done, i.e. you cannot access the txtFile.responseText right after txtFile.send(null) as there is no any reponse by that moment. The response (i.e. the content of the textfile.txt) will be available only when onreadystatechange will be invoked with readyState === 4 and only in that moment you can save it into the value variable.
<input type="file"/>, you can then use FileReader to output the contents.file:///?