Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript (Angular) - read text file line by line

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.

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"});
}

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);
    });
  }

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);
}

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.

like image 623
Lukasz Nowak Avatar asked Mar 18 '19 09:03

Lukasz Nowak


1 Answers

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?

like image 99
Ashish Ranjan Avatar answered Oct 14 '22 22:10

Ashish Ranjan