首页 > 解决方案 > 试图将文本文件加载到

标签,为什么它不起作用?

问题描述

我一直在查看与此相关的其他 stackoverflow 问题,但我不明白为什么这段代码不起作用。现在我首先只是试图将文本获取到控制台日志,看看它是否会起作用。我正在逐行跟踪其他人的代码,它不适用于这种情况,我不确定为什么。

const file = "1.txt";

let reader = new FileReader();

reader.onload = (e) => {
    const file = e.target.result;
    const lines = file.split(/\r\n|\n/);
    console.log(lines.join('\n'));
};

reader.readAsText(file); 

标签: javascriptfileapi

解决方案


对于其他遇到此特定问题的人,我发现 fetch() 函数是我的问题的关键。如果您执行以下操作:

fetch('1.txt')
  .then(response => response.text())
  .then(data => {
      // Do something with your data
      console.log(data);
  });

感谢我收到的所有评论,它帮助我找到了这个解决方案!


推荐阅读