简体   繁体   中英

Read .txt file with javascript

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.

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 ajaxyou 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM