TypeScript(角度)-逐行读取文本文件 [英] TypeScript (Angular) - read text file line by line

查看:2006
本文介绍了TypeScript(角度)-逐行读取文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在逐行读取文本文件时遇到问题.使用console.log(file)可以很好地工作,但是我需要每一行对它们进行处理,所以这是我到目前为止所做的.

I have a problem with reading a text files LINE BY LINE. Using console.log(file) works perfectly fine, but I need each particular line to do something with them, so here's what I've done so far.

在api.service.ts中,我有一个从服务器下载文件的函数,该函数本身看起来像这样:

In api.service.ts I have a function that downloads the file from the server, and the function itself looks like this:

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

然后在app.component.ts中定义一个私有的'resultFile:File'字段,并将传入文件分配给该变量

Then in app.component.ts I define the private 'resultFile: File' field and assign the incoming file to this variable

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

As I mentioned before printing the content of resultFile using console.log() works just fine. File is properly formatted (with new lines), but when I loop through the resultFile

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

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

It prints each single character instead of each single line. I think the problem may be the responseType: "text" which converts the content to plain string, but I couldn't find any solution for this. Sorry for such dumb question, but I've never used JS/TS before.

推荐答案

尝试使用newLines拆分行:

Try splitting the lines with newLines:

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

请参阅此以查看行分隔符:执行行Windows和Linux的结尾是否不同?

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

这篇关于TypeScript(角度)-逐行读取文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆