6

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.

1 Answer 1

9

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?

Sign up to request clarification or add additional context in comments.

1 Comment

Works perfectly fine. Thank you :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.