Javascript读取本地txt文件

以下代码实现javascript读取本地文件打印到浏览器中

  1. function load(name) {
  2.     let xhr = new XMLHttpRequest(),
  3.         okStatus = document.location.protocol === "file:" ? 0 : 200;
  4.     xhr.open('GET', name, false);
  5.     xhr.overrideMimeType("text/html;charset=utf-8");//默认为utf-8
  6.     xhr.send(null);
  7.     return xhr.status === okStatus ? xhr.responseText : null;
  8. }
  9.  
  10. let text = load("文件名.txt");
  11.  
  12. console.log(text); //输出到浏览器控制器中
  13.  
  14. //document.write(text); //打印在网页中
  15.  
  16. //document.write("<pre>"+text+"<pre/>"); //解决txt的换行无法打印到网页上的问题
原文地址:https://www.cnblogs.com/jscs/p/13444671.html