好的,我有一个程序,它将一些特定数据输出到制表符分隔的变量文件中。
我一直在使用 Excel 打开和查看文件内容,但是我发现 Excel 坚持锁定它打开的每个文件,这非常烦人,因为如果我在 Excel 中打开文件,我的程序就会崩溃......但我真的很喜欢每次运行程序后数据都会整齐地更新,因此我不必一直关闭并重新打开文件。
因此,我决定使用 Javascript 解析文件并将其显示在 html 表格中是最简单的,而且确实如此。我很快就把一些东西撞到了一起。现在,如果我将文件保留在显示状态,我的程序不会崩溃,但是,它仍然不会更新......而且我每次都必须打开新生成的文件。
所以,我想知道是否有一种机制可以让我的 Javascript 以某种方式通知另一个进程对文件的更改?我知道这不太可能,但我想避免出于明显的原因简单地轮询文件。
我对 JS 非常熟悉,但 HTML5 和新的 API 对我来说都是陌生的。
我不相信File API http://www.w3.org/TR/FileAPI/有文件更改的任何事件,只有进度事件等。
2020 年 8 月更新:以下替代方案不再有效,并且规范特别禁止它 https://w3c.github.io/FileAPI/#file-section说的是File
对象的信息必须反映基础文件在被选择时的状态。从规格来看:
用户代理应努力将文件对象的快照状态设置为引用时磁盘上底层存储的状态。如果在获取引用后在磁盘上修改文件,则文件的快照状态将与底层存储的状态不同。
You could use polling. Remember the lastModifiedDate http://www.w3.org/TR/FileAPI/#dfn-lastModifiedDate of the File
, and then when your polling function fires, get a new File
instance for the input and see if the lastModifiedDate
has changed.
这在 Chrome 上适用于我,例如:实时复制 http://jsbin.com/ajepef/1 | Source http://jsbin.com/ajepef/1/edit
(function() {
var input;
var lastMod;
document.getElementById('btnStart').onclick = function() {
startWatching();
};
function startWatching() {
var file;
if (typeof window.FileReader !== 'function') {
display("The file API isn't supported on this browser yet.");
return;
}
input = document.getElementById('filename');
if (!input) {
display("Um, couldn't find the filename element.");
}
else if (!input.files) {
display("This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!input.files[0]) {
display("Please select a file before clicking 'Show Size'");
}
else {
file = input.files[0];
lastMod = file.lastModifiedDate;
display("Last modified date: " + lastMod);
display("Change the file");
setInterval(tick, 250);
}
}
function tick() {
var file = input.files && input.files[0];
if (file && lastMod && file.lastModifiedDate.getTime() !== lastMod.getTime()) {
lastMod = file.lastModifiedDate;
display("File changed: " + lastMod);
}
}
function display(msg) {
var p = document.createElement('p');
p.innerHTML = msg;
document.body.appendChild(p);
}
})();
<input type='file' id='filename'>
<input type='button' id='btnStart' value='Start'>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)