读取文件的简单javascript程序

Simple javascript program reading a file

本文关键字:javascript 程序 简单 文件 读取      更新时间:2023-09-26

我正在写一个简单的脚本,它将读取.txt文件。我在让它工作时遇到了很多麻烦,现在我想升级它。基本上,我正在寻找一个选项,在打开并读取文件之前停止程序。我试着放一个while()来等待某个变量的更改,但这会暂停整个程序,从而无法点击打开的文件。

HTML:

<html>
<head>
</head>
<body>
<input type="file" id="fileInput">  
<script src="1dn.js"></script>
</body>
</html>

Javascript:

var string;
window.onload = function() {
var fileInput = document.getElementById('fileInput');   
fileInput.addEventListener('change', function(e) {      
    var file = fileInput.files[0];      
    var reader = new FileReader();
    reader.onload = function(e) {                   
        string = reader.result;             
        alert(string);
    }
    reader.readAsText(file);
});
}
*** wait here until file is opened and read
*** do some other stuff

您可以使用添加when函数的库,也可以自己用纯JS实现一个函数(如果您喜欢的话):

function when(conditionFunc, execFunc, interval) {
    if (conditionFunc()) {
        execFunc();
    } else {
        setTimeout(function() { when(conditionFunc, execFunc, interval);}, interval);
    }
}

你可以在这里阅读更多关于函数的信息。像这样使用:

when(function() {
    return string;
}, function() {
    // do stuff
}, 500);

如果希望// do stuff在字符串更改时执行,只需将return string;更改为比较新字符串值和旧字符串值的条件即可。

好吧,如果您在一个函数中封装所有必须在打开和读取文件后才能执行的代码,那么在调用该函数之前,它将被解析但不会执行。

然后在回调结束时调用函数(事件侦听器的参数中给定的函数)。

编辑:很抱歉我放restOfCode()的地方不清楚。它必须onload回调内。

您将无法摆脱文件输入上的事件侦听器,因为如果不是来自用户操作,浏览器实际上会阻止您访问任何客户端本地文件。这是一种安全措施,可防止恶意网站在未经访问者同意的情况下访问访问者的文件。

结果:

var string;
window.onload = function() {
    var fileInput = document.getElementById('fileInput');   
    // You need user input for the browser to allow you reading local files.
    // This is a security measure to protect the user.
    fileInput.addEventListener('change', function(e) {      
        var file = fileInput.files[0];      
        var reader = new FileReader();
        reader.onload = function(e) {                   
            string = reader.result;             
            alert(string);
            // At this point only you are sure your file is opened and read.
            restOfCode();
        }
        // Open the file and start reading.
        reader.readAsText(file);
    });
}
// *** wait here until file is opened and read
// the function below is parsed but not executed, since it is not called
function restOfCode() {
    //*** do some other stuff
}