Javascript从当前目录读取文本文件

Javascript read text file from current directory

本文关键字:取文本 文件 读取 当前目录 Javascript      更新时间:2023-09-26

如何在没有jquery的情况下使用javascript从当前目录读取文本文件(text1.txt)。我尝试了以下代码:

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

FileReader API通常用于读取通过一个<input type="file">选择的文件。它不能读取任意文件。readAsText方法期望接收一个Blob或File对象,而不是一个包含文件名的字符串。

要读取HTML文档的兄弟文件,请使用XMLHttpRequest。如果通过HTTP(S)加载文档,这将可靠地工作。如果你使用本地HTML文档(通过file: URI),那么许多浏览器的安全限制将阻止它工作(而你应该运行本地web服务器)。

选项A,您的用例阻止您使用http或php服务器 你可以使用script include将本地内容作为变量包含在javascript中。如果你是在本地打开页面,作为一个目录中的文件,这是在网页中包含本地内容的唯一方法。

要包含本地内容,请将其置于其他脚本标签之上:

<script src="text1.txt"></script>
并编辑text1.txt文件,使其将所有内容分配给一个变量:
gbl_text=`...contents of my text file...
...more contents...
...and so on....   
`

您可以使用脚本来创建这个包含文件,例如(在波浪键~下面使用'勾号'):

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

然后根据需要在javascript中使用gbl_text变量…

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

选项B,您的用例将允许您使用php-cli内置服务器如果您能够运行php-cli,您可以在内置的php web服务器上打开页面,并通过php调用读取和写入本地内容。要在linux上安装和使用php,

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

所以,不是打开你的html文件,你会打开一个http网页:

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

现在本地网页是由一个实际的(本地)http服务器提供的php支持,你可以用它来操作本地文件。

下面是一个简单的例子,展示了如何使用jQuery和php读取和写入本地文件。下载并包括jQuery(见jQuery.com)在你的html文件。

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; 
  }
?> 

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>

请区分两种阅读文件:

  • 读取"from internet" -使用XMLHttpRequest读取任何类型的文件
  • 读取"从客户端"-使用文件阅读器或<input type="file">

制作一个小小的iframe。在那里加载文件。使用iframe.innerHTML

读取