am trying to read few lines from a txt file using JS,and i have this code but its not working for some reason,,
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.OpenTextFile("C:\\wamp\\www\\22.txt", 1, true);
var row = s.ReadLine();
alert(row);
any suggestions?!
am trying to read few lines from a txt file using JS,and i have this code but its not working for some reason,,
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.OpenTextFile("C:\\wamp\\www\\22.txt", 1, true);
var row = s.ReadLine();
alert(row);
any suggestions?!
Share Improve this question edited Feb 27, 2011 at 20:16 Chandu 83k19 gold badges135 silver badges135 bronze badges asked Feb 27, 2011 at 20:13 dimazaiddimazaid 1,6713 gold badges22 silver badges24 bronze badges 5- 1 When you say not working.. what is not working? Are you testing this in IE or any other browser? – Chandu Commented Feb 27, 2011 at 20:15
- i tried firefox and chrome and yeah no output! – dimazaid Commented Feb 27, 2011 at 20:16
- 1 Most browsers won't allow that. you could run the script from the console, and it would work. But not within a browser, unless the page itself is loaded with high trust. In IE there are security zones you can set for this; not sure about the other browsers. – Cheeso Commented Feb 27, 2011 at 20:18
-
You could install a web server and then use
XMLHttpRequest
. Working locally has its disadvantages. – pimvdb Commented Feb 27, 2011 at 20:29 - The above will only work out of the box if you save the code with extension .HTA for html application – mplungjan Commented Feb 27, 2011 at 22:08
3 Answers
Reset to default 3Make sure your browser has the right permissions to perform that kind of operation. Usually, browsers won't allow direct file system access by default.
Only IE supports ActiveXObject
. Trying to use ActiveXObject
on any other browser will fail because there is no such variable defined.
You need to either limit yourself to IE, write a browser plugin instead, or give up trying to get file system access on other browsers and proxy files through a server instead.
If you're running WAMP anyway, just use standard AJAX to fetch the file 22.txt from the server. The easiest way is to use jQuery, where the code would be:
$.get("22.txt", function(data) {
alert(data);
}
You can search for how to do this without jQuery if you wish.