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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With