有什么方法可以让 javascript 读取具有自定义扩展名的文件?

让我们考虑一个自定义扩展.cst,我们有一个 JavaScript 函数CSTReader()专门设计用于读取.cst文件。这是一个例子:

文件.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.

那么,可以制作CSTReader()吗?或者在 javascript 中是不可能的?如果没有,有什么替代方法吗?还是只是浪费时间?

提前致谢


德玛西亚99
浏览 188回答 1
1回答

牧羊人nacy

您可以使用FileReader对象来执行此操作。它也适用于自定义扩展。查看https://developer.mozilla.org/fr/docs/Web/API/FileReader以获取文档。如果您的文件包含纯文本,则可以使用该readAsText方法。在您的示例中,您可以执行以下操作:<input type="file" onchange="readFile"/> // put your file here<script>function readFile(e) {&nbsp; let file = e.target.files[0] // get the file&nbsp; let fileReader = new FileReader(); // instanciate Filereader&nbsp; fileReader.onloadend = function () { // bind your function to the onloadend method. It will be executed once the file is read.&nbsp; &nbsp; console.log(filereader.result);&nbsp; &nbsp; // do whatever you want with the content&nbsp; };&nbsp;&nbsp; fileReader.readAsText(file); // read the file, whatever the extension is.}</script>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript