I am trying to load a text file into my JavaScript file and then read the lines from that file in order to get information, and I tried the FileReader but it does not seem to be working. Can anyone help?
function analyze(){
var f = new FileReader();
f.onloadend = function(){
console.log("success");
}
f.readAsText("cities.txt");
}
(fiddle: https://jsfiddle.net/ya3ya6/7hfkdnrg/2/ )
Html:
Js:
Javascript doesn't have access to the user's filesystem for security reasons.
FileReader
is only for files manually selected by the user.Yeah it is possible with FileReader, I have already done an example of this, here's the code:
It's also possible to do the same thing to support some older versions of IE (I think 6-8) using the ActiveX Object, I had some old code which does that too but
its been a while so I'll have to dig it upI've found a solution similar to the one I used courtesy of Jacky Cui's blog and edited this answer (also cleaned up code a bit). Hope it helps.Lastly, I just read some other answers that beat me to the draw, but as they suggest, you might be looking for code that lets you load a text file from the server (or device) where the JavaScript file is sitting. If that's the case then you want AJAX code to load the document dynamically which would be something as follows:
This can be done quite easily using javascript XMLHttpRequest() class (AJAX):
my example