javascript - 使用 setInterval 和 FileReader 定期记录文件的内容

标签 javascript reactjs setinterval filereader

我将此 f-tion 附加到 <input type="file">元素作为“onclick”处理程序:

handleWatch(event) {

  event.preventDefault();
  const file = event.target.files[0];
  if (!file) {
    return;
  }

  const reader = new FileReader();

  setInterval(() => {

    reader.onload = async function(e) {
      const content = e.target.result;

      const lines = content.split('\n').filter((line) => {
        return !line.beginsWith('#') && !(line === "");
      });
      const nLines = lines.length - 1;

      console.log("number of lines in file: " + nLines);

    }
    reader.readAsText(file, 'UTF-8');

  }, 1500);

}

这个想法是创建一个记录器,定期检查文件内容(由用户选择)是否有更改并保存到数据库(为了清楚起见,删除了此代码)。间隔执行有效(记录到控制台),直到内容确实发生更改时,reader.onload 中的任何指令都不会被执行。

最佳答案

从 FileAPI 规范中,您可以在此处阅读:https://www.w3.org/TR/FileAPI/#security-discussion

Important security considerations include preventing malicious file selection attacks (selection looping), preventing access to system-sensitive files, and guarding against modifications of files on disk after a selection has taken place.

由于本节内容丰富,因此可能并非所有浏览器都实现了此安全功能。您使用的浏览器似乎遵循规范(我猜所有浏览器都遵循规范)。

我们还可以阅读以下内容:

This is a non-trivial requirement to implement for user agents, and is thus not a must but a should [RFC2119]. User agents should endeavor to have a File object's snapshot state set to the state of the underlying storage on disk at the time the reference is taken. If the file is modified on disk following the time a reference has been taken, the File's snapshot state will differ from the state of the underlying storage. User agents may use modification time stamps and other mechanisms to maintain snapshot state, but this is left as an implementation detail.

因此,即使浏览器在文件更改后没有阻止您,那么当用户选择该文件时您也会获得该文件的快照。

关于javascript - 使用 setInterval 和 FileReader 定期记录文件的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37562621/

相关文章:

javascript - AngularJS 破坏了路由 url

javascript - 我计算得到该月的第一天,但​​得到了最后一天

reactjs - 无法创建 react 项目

reactjs - ReactJS 中的文件命名约定?

javascript - 非同步启动 Javascript 间隔并在运行 3 次后停止

javascript - setInterval 不调用函数

javascript - Bootstrap 3 - 在静态页眉和页脚之间填充页面容器(填充宽度和高度)

javascript - 使用 ajax 调用 react 组件 - 生命周期

javascript - 错误 TS2356 表示数字类型变量必须是类型 'number' 的算术操作数

javascript - 将时间戳转换为新日期的问题