读取文件的简单javascript程序
Simple javascript program reading a file
我正在写一个简单的脚本,它将读取.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
}
相关文章:
- 为什么我的javascript程序没有将其转换为整数而不是字符串
- 为什么Javascript程序员更喜欢在代码中重复字符串作为常量,而不是使用枚举类型的对象
- 基本的HTML Javascript程序.这是怎么回事
- 如何重复Javascript程序
- 我没有'我不明白“;temp<<=y"在这个javascript程序中执行
- Javascript程序,如果语句有困难
- JavaScript程序,随机生成一百次个位数(0,1,…9),并输出生成了多少个0s、1s、2s……9s
- 可以编写一个预先加载所有图像和视频的JavaScript程序
- 这个JavaScript程序是如何工作的
- JavaScript 程序中的错误
- 编写一个JavaScript程序来计算闰年
- 将 JavaScript 程序从 JSON 转换为 XML
- 基本的Javascript程序,需要帮助
- 如何结束 JavaScript 程序中间程序
- 为什么 JavaScript 程序无法运行
- JavaScript 程序中的多个文件
- 如何重置我的 Javascript 程序
- 在javascript程序中使用c动态链接库
- 如何让此 JavaScript 程序根据提示的输入向对象属性发出警报
- 购物清单 Javascript 程序列表项的文本格式不正确