首页 > 解决方案 > TypeScript (Angular) - 逐行读取文本文件

问题描述

我在逐行阅读文本文件时遇到问题。使用 console.log(file) 效果很好,但我需要每个特定的行对它们做一些事情,所以这就是我到目前为止所做的。

在 api.service.ts 我有一个从服务器下载文件的函数,函数本身如下所示:

getFile(url: string): Observable<File> {
  return this.httpClient.get<File>(url, {responseType: "text"});
}

然后在 app.component.ts 我定义了私有的“resultFile:File”字段并将传入的文件分配给这个变量

getFile() {
    this.apiService.getFile('http://127.0.0.1:8000/media/results/MINERvA/CC0pi/v1.0/nuwro.txt').subscribe(file => {
      this.resultFile = file;
      console.log(this.resultFile);
    });
  }

正如我在使用 console.log() 打印 resultFile 的内容之前提到的那样工作得很好。文件格式正确(带有新行),但是当我遍历 resultFile

for (const line of resultFile){
  console.log(line);
}

它打印每个字符而不是每一行。我认为问题可能是 responseType: "text" 将内容转换为纯字符串,但我找不到任何解决方案。抱歉这个愚蠢的问题,但我以前从未使用过 JS/TS。

标签: angulartypescriptfile

解决方案


Try splitting the lines with newLines:

for (const line of resultFile.split(/[\r\n]+/)){
  console.log(line);
}

Refer this to see line seperators: Do line endings differ between Windows and Linux?


推荐阅读