1

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?!

Chandu
  • 81,493
  • 19
  • 133
  • 134
dimazaid
  • 1,673
  • 3
  • 22
  • 24
  • 1
    When you say not working.. what is not working? Are you testing this in IE or any other browser? – Chandu Feb 27 '11 at 20:15
  • i tried firefox and chrome and yeah no output! – dimazaid Feb 27 '11 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 Feb 27 '11 at 20:18
  • You could install a web server and then use `XMLHttpRequest`. Working locally has its disadvantages. – pimvdb Feb 27 '11 at 20:29
  • The above will only work out of the box if you save the code with extension .HTA for html application – mplungjan Feb 27 '11 at 22:08

3 Answers3

3

Make sure your browser has the right permissions to perform that kind of operation. Usually, browsers won't allow direct file system access by default.

Pablo Santa Cruz
  • 176,835
  • 32
  • 241
  • 292
2

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.

Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
  • This generally won't work from IE either, as the object in question is not marked Safe-For-Scripting. – EricLaw Feb 27 '11 at 23:55
1

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.

zacharyliu
  • 25,578
  • 4
  • 21
  • 15