最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Javascript read text file from current directory - Stack Overflow

programmeradmin9浏览0评论

How to read text file (text1.txt) from current directory using javascript without jquery. I tried the following code.

var file = "text1.txt";
var reader = new FileReader();
var result = reader.readAsText(file);
console.log(result);

How to read text file (text1.txt) from current directory using javascript without jquery. I tried the following code.

var file = "text1.txt";
var reader = new FileReader();
var result = reader.readAsText(file);
console.log(result);
Share Improve this question asked Mar 25, 2013 at 12:44 kklwkklw 8883 gold badges14 silver badges28 bronze badges 4
  • 2 what do you mean by current directory – Arun P Johny Commented Mar 25, 2013 at 12:45
  • 1 The user must first "upload" the file to the page before you can select it. You can't access a file without the user consent. Or is the file on your server? Then you need Ajax, not FileReader. – JJJ Commented Mar 25, 2013 at 12:47
  • looking at the API docs, this is an asynchronous operation. Your result will only be valid when loading is done. developer.mozilla.org/en-US/docs/DOM/… – Thilo Commented Mar 25, 2013 at 12:47
  • My result from the above code is undefined. Not a file that is uploaded by user. Is a text file together with my html file and javascript file in a common file directory. – kklw Commented Mar 25, 2013 at 12:49
Add a comment  | 

4 Answers 4

Reset to default 8

The FileReader API is usually used to read files selected via the an <input type="file">. It cannot read arbitrary files. The readAsText method expects to receive with a Blob or a File object, not a string containing a file name.

To read files that are siblings of the HTML document, use XMLHttpRequest. This will reliably work if you load the document over HTTP(S). If you are using a local HTML document (via a file: URI) then security restrictions in many browsers will prevent it from working (and you should run a local web server instead).

Option A, Your use-case prevents you from using an http or php server. You can include local content in your javascript as a variable using a script include. If you are opening the page locally, as a file from a directory, this is the only way to include local content in the web page.

To include local content, put this above your other script tag:

<script src="text1.txt"></script>

and edit your text1.txt file so it assigns all the content to a variable:

gbl_text=`...contents of my text file...
...more contents...
...and so on....   
`

You can use a script to create this include file, for example (use the ` tick mark below the tilde ~ key):

echo -n "var gbl_text=\`" > text1.txt
cat your-original-file.txt >> text1.txt
echo "\`" >> text1.txt

Then use the gbl_text variable in your javascript as needed...

function dosomething()
{
  if (typeof(gbl_text)=='undefined'){
    setTimeout('dosomething()',500)  //call back until defined
  }else{
    console.log(gbl_text)
  }
}

Option B, Your use-case would allow you to use the php-cli built-in server. If you are able to run php-cli, you can open the page on the built-in php webserver, and read and write local content with a php call. To install and use php on linux,

sudo apt install php7.0-cli
#To use the php built-in webserver, run:
php -S localhost:8000 -t /path/to/your/content

So, instead of opening your html as a file, you would open as an http web page:

firefox http://localhost:8000/mypage.html
#or browser of choice

Now the local webpage is being served by an actual (local) http server with php support, and you can manipulate local files with it.

Here is simple example showing how to read and write to a local file using jQuery and php. Download and include jQuery (see jQuery.com) in your html file.

Contents of dofile.php:

<?php 
$dowhat  = $_REQUEST['dowhat'];
  if ($dowhat=='save'){
    $myvar = $_REQUEST['myvar'];
    file_put_contents('myfile', $myvar); 
  }elseif($dowhat=='read'){
    $myvar=file_get_contents('myfile');
    echo $myvar; 
  }
?> 

Contents of mypage.html:

<script src='jquery-3.2.1.js';></script>
<!--make sure the filename matches the jQuery you use-->

<script>
function savevar(){
  var myvar=document.getElementById('mytxt').value
  var path="dofile.php?dowhat=save&myvar="+myvar 
  $.get(path, function(data){
    console.log("saved ...\n"+myvar)
    alert("saved ...\n"+myvar)
  });
}

function clearbox(){
  document.getElementById('mytxt').value='reading file...'
  setTimeout('getvar()',1000)
}

function getvar(){
  var path="dofile.php?dowhat=read"
  $.get(path, function(data){
    console.log(data);
    document.getElementById('mytxt').value=data
    /*do other things with data here*/;
  });
}
</script>

<html>
Type something in the text box.<br>
Use the Read and Write buttons to verify <br>
text is saved and read back.<br> 
<input id='mytxt' value='type text here' onclick=document.getElementById('mytxt').value=''><br>
<input type='button' value='Save' onclick=savevar() ><input type='button' value='Read' onclick=clearbox() >

</html>

Please distinguish 2 kinds of reading files:

  • reading "from internet" - use XMLHttpRequest to read any kind of file
  • reading "from client" - use FileReader or <input type="file">

make a tiny iframe. load the file there. read it with iframe.innerHTML

发布评论

评论列表(0)

  1. 暂无评论