如何从硬编码路径和文件名逐行读取Java Script中的文件? [英] How to read file in Java Script line by line from hardcoded path and name of the file?

查看:80
本文介绍了如何从硬编码路径和文件名逐行读取Java Script中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用Java脚本读取文件.最好是逐行读取,但是也有可能一次读取整个文件.通常在Web上有很多实现,但是我想以非常简单的方式读取文件,方法是在Java Script代码中输入硬编码的路径和文件名,而不是任何按钮或类似的东西.下面的伪代码:

 <!DOCTYPE html>< html>< body>< script type ="text/javascript">var file = FileReader("home/test.txt");//文件的硬编码路径和名称var listOfLines = [];var line = file.readLine();while(line!= eof){listOfLines.push(file.readLine());file.readLine();}</script></body></html> 

是否有可能做这样的事情.谢谢.

解决方案

FileReader运行良好且受到良好支持,请参阅:

https://caniuse.com/#search=FileReader

甚至IE也有部分支持.

但是它只能读取用户返回的文件.您无法从开发人员读取任何带有硬编码路径的文件.当然,出于安全原因,浏览器中的javascript引擎在沙箱中运行.

PS另外,要从javascript读取较大的csv文件,建议使用这个库,该库我已成功使用了很多次:

https://www.papaparse.com/

参考:

https://www.w3.org/TR/FileAPI/

https://www.w3.org/TR/FileAPI/#dfn-filereader

https://developer.mozilla.org/it/docs/Web/API/FileReader

I would like to read file in Java Script. The best it would be to read line by line, but there is also possibility to read the whole file at once. Generally on the web there is quite a lot of implementations, but I would like to read a file in very simple way by entering, hardcoded path and file name in the Java Script code, not but any buttons or something like this. The pseudo code below:

<!DOCTYPE html>
<html>
<body>
    <script type="text/javascript">
        var file = FileReader("home/test.txt");//hardcoded path and name of the file
        var listOfLines = [];
        var line = file.readLine();
        while(line != eof) {
            listOfLines.push(file.readLine());
            file.readLine();
        }
    </script>
</body>
</html>

Is there such possibility to do something like this. Thank you.

解决方案

FileReader is working well and it is well supported, see:

https://caniuse.com/#search=FileReader

even IE has a partial support.

But it can read ONLY file returned from the user. You cannot read any file with an hardcoded path from the developer. Of course that is for security reasons, the javascript engine in the browser runs in a sandbox.

PS Also, to read big csv files from javascript, I suggest this library, that I used many times with success:

https://www.papaparse.com/

reference:

https://www.w3.org/TR/FileAPI/

https://www.w3.org/TR/FileAPI/#dfn-filereader

https://developer.mozilla.org/it/docs/Web/API/FileReader

这篇关于如何从硬编码路径和文件名逐行读取Java Script中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆