Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript read text file from current directory

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);
like image 542
kklw Avatar asked Jan 14 '23 20:01

kklw


2 Answers

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

like image 128
Quentin Avatar answered Jan 19 '23 10:01

Quentin


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>
like image 22
Ken H Avatar answered Jan 19 '23 10:01

Ken H