有没有办法让JavaScript读取自定义扩展名的文件?

3

假设我们有一个自定义扩展名为.cst,并且我们有一种特别设计用于读取.cst文件的JavaScript函数CSTReader()。以下是一个示例:

files.cst:

I am a cst file. I have data in me such that I am readable by javascript.

index.js:

 document.write("Reqd Output : " +  CSTReader("files.cst") );

输出:

Reqd Output : I am a cst file. I have data in me such that I am readable by javascript.

那么,在JavaScript中是否可以使用CSTReader()?如果不行,有没有替代方案?还是说这样做只是浪费时间?

提前感谢。


您可以使用FileReader加载任何文件。文件内容的可读性取决于它的类型。 - Gavin
客户端上的本地文件,还是Web服务器上的文件?读取后者意味着一种常规的AJAX请求,没有任何特殊之处。 - 04FS
1个回答

3
您可以使用FileReader对象来实现。它也可以处理自定义扩展名。 请参考https://developer.mozilla.org/zh-CN/docs/Web/API/FileReader以获取文档。
如果您的文件包含纯文本,则可以使用readAsText方法。
在您的示例中,您可以这样做:
<input type="file" onchange="readFile"/> // put your file here
<script lang="js">

function readFile(e) {
  let file = e.target.files[0] // get the file

  let fileReader = new FileReader(); // instanciate Filereader
  fileReader.onloadend = function () { // bind your function to the onloadend method. It will be executed once the file is read.
    console.log(filereader.result);
    // do whatever you want with the content
  }; 
  fileReader.readAsText(file); // read the file, whatever the extension is.
}
</script>

您还可以查看这个演示。

祝好运!


要从URL加载文件,您可以使用Fetch API而不是FileReader。 - Anderson Green

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接