0

I want to use javascript to read a file called "orca.txt" to get a number (counter). I tried to do that:

var contador=0; 

var fr = new FileReader();  
fr.onload = function(e) {contador = e.target.result;};

fr.readAsText("orca.txt");

I know how to do that with an "input" but i don't want user choice a file... the file is always orca.txt Can anyone help me?

Andreas
  • 21,535
  • 7
  • 47
  • 56
  • 2
    [How do I format my posts using Markdown or HTML?](https://stackoverflow.com/help/formatting) – Andreas Apr 06 '21 at 14:41
  • 2
    That would be a huge security problem, if a script could freely choose the file that should be read. – Andreas Apr 06 '21 at 14:42
  • 1
    It's not possible to read an arbitrary file on the user's computer since it would be a huge security vulnerability. – shreyasm-dev Apr 06 '21 at 14:43
  • You can't. Just imagine if a page you load just try to load file on your computer. How would you react ? – Vollfeiw Apr 06 '21 at 14:44
  • You need to use a `file input` to initialise this sort of process – Professor Abronsius Apr 06 '21 at 14:47
  • But it's not a file from user's computer... in my site, i've a file in folder, index.html must read it... it isnt an inputed file... Can I? – Mario Augusto Apr 06 '21 at 14:53
  • @Vollfeiw you re right... but i wanna read my file, in my server, just to get some configuration.. – Mario Augusto Apr 06 '21 at 14:54
  • You might be able to use [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) if the server is serving the file – shreyasm-dev Apr 06 '21 at 14:56
  • Then you can't with javascript. Your javascript file is running on client side, not server side. If you need to get a document from your client side, you will have to make it public on your server, wich can be bad if this is a confidential file. In this case, you will need to have scripts running on server to read the file before (php could be a good start) sending the html page. – Vollfeiw Apr 06 '21 at 14:58
  • Thank you guys... i will try – Mario Augusto Apr 06 '21 at 15:04
  • Can you give more information about your server ? Are you running a node server ? Apache / nginx ? Can your txt file be used before serving the html file ? Can it be served as a public file, or do you need it to be private ? We could give you a slightly more precise answer by knowing what's your goal and setup. – Vollfeiw Apr 06 '21 at 15:09

0 Answers0