-3

Can you read a txt file in javascript with the file path in the code? Not by selecting the file from the open file window.

Alb
  • 43
  • 1
  • 5

2 Answers2

1

If the textfile is on a local or private PC

As you may understand if you could read a textfile that is stored on a user's filesystem everyone would be able to steal private data, so in short NO you can't.

If your textfile is on your server

ajax

function ajax(a,b,c){ // Url, Callback, just a placeholder
 c=new XMLHttpRequest;
 c.open('GET',a);
 c.onload=b;
 c.send()
}

how to use:

ajax('http://YOURSERVER/yourtextfile.txt',function(){
 alert(this.response);
});

more about the above function

If your textfile is on a different server

When you tray to access other servers with ajax you need to be allowed to access that file. some sites allow it by returning

Access-Control-Allow-Origin: *

in the response heaeders.so the above ajax function would work properly.


Then there are other ways to get data from your or other servers that i prefer over ajax:

websockets & SSE.. but those need a specific interface like php or nodejs.

Another option is if the file is on your private pc and you just want to send some data that is stored in a specific textfile everytime you update:

Just install nodejs or a free PHP server and create some sort of cron job to check a specific folder everyonce a while. When the file is updated just send it to your online server. Again the online host needs at least PHP ASP or some sort of serverside scripting.

Community
  • 1
  • 1
cocco
  • 16,442
  • 7
  • 62
  • 77
0

you can use XHR (XML Http Request). Below is an example for reading a '.txt' file. You can have this in an html file and will need to run a simple server using NodeJS, Python Simple Server or any other server that you are comfortable with.

1 If you have python:

python -m SimpleHTTPServer 8000

2 Example (readtxt.html):

<script type="text/javascript">
var request = new XMLHttpRequest();
request.open('GET', 'filename.txt', false);  // `false` => synchronous request
request.send(null);

if (request.status === 200) {
  console.log(request.responseText);
}
</script>

3 Open: http://localhost:8000/readtxt.html

4 Check the browser console for content read from the txt file.

You can read this for more detailed information,

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests#Asynchronous_request

Hamzeen Hameem
  • 2,360
  • 1
  • 27
  • 28