angularcsvfilereaderwebapifileapi

File reader not giving out the results properly for certain csv files


I'm new to file reader. While adding a csv file, the file reader sometimes gives out the results like this

Pillar ID,Pillar Name,Question ID,Question,Question Description,Best Practice ID,Best Practice,Best Practice Description,Risk,Recommendation,Policies\r\n

but sometimes it gives out the results like this

Pillar ID,Pillar Name,Question ID,Question,Question Description,Best Practice ID,Best Practice,Best Practice Description,Risk,Recommendation,Policies\r

it is not adding the new line, so the content is not getting parsed correctly. Don't find any difference in the file either. What could be the issue, have you faced this

Didn't try anything, as this is from FileReader API itself.


Solution

  • Just correct you content file before doing your job with it

    HTML

    <input type="file" (change)="onFileSelected($event)" accept=".csv">
    

    TS import { Component } from '@angular/core';

    @Component({
      selector: 'app-file-reader',
      templateUrl: './file-reader.component.html',
      styleUrls: ['./file-reader.component.css']
    })
    export class FileReaderComponent {
    
      constructor() { }
    
      onFileSelected(event: any) {
        const file: File = event.target.files[0];
        if (file) {
          this.readFile(file);
        }
      }
    
      readFile(file: File) {
        const reader = new FileReader();
    
        reader.onload = (e) => {
          let csvData: string = reader.result as string;
          csvData = this.correctLines(csvData);
          console.log(csvData);
        };
    
        reader.onerror = (e) => {
          console.error('Error occurred while reading the file');
        };
    
        reader.readAsText(file);
      }
    }
    
    private correctLines(data):string {
        let res = data.replace(/\n\r/g, '\r');
        res = res.replace(/\r/g, '\n\r');
        return res;
    }