Skip to content
Advertisement

How to parse a text file with delimiter using FileReader

I working on an Angular project which I have to upload a .txt file then parse all its lines loop over them. I used this peace of code but it just returns me a text format just like opening it in notepad and that’s not what I want, my goal is to every single data with the delimiter ; and console that in an array ob objects.

this is my code:

  fileChangeListener($event: any): void {
    const file = $event.target.files[0];
    let fileReader = new FileReader();
    fileReader.onload = (e) => {
      let data = fileReader.result;
      console.log("FileREAAAAAAAAAAADER n" + data);

    }
    fileReader.readAsText(file);

this is my .txt file structure:

1234;06/07/22;06/07/22;VRT;  ;31070;some String content;some String content; ;147.10;A;1234
1234;06/07/22;06/07/22;VRT;  ;31070;some String content;some String content; ;147.10;A;1234
1234;06/07/22;06/07/22;VRT;  ;31070;some String content;some String content; ;147.10;A;1234
1234;06/07/22;06/07/22;VRT;  ;31070;some String content;some String content; ;147.10;A;1234
1234;06/07/22;06/07/22;VRT;  ;31070;some String content;some String content; ;147.10;A;1234

in console, the code I wrote displays just like the above structure where the output should be like this:

enter image description here

Advertisement

Answer

I have modified the your code to make a string[][] like you needed.

Not knowing what you want to do with the data, it is just local to that function.

dummyArr is what you want 🙂

Kept it kinda bland so you can modify it to your future needs

Hope this helps!

fileChangeListener(event: any): void {
    console.log("submitted here")
    const file = event.target.files[0];
    let fileReader = new FileReader();
    fileReader.onload = (e) => {
      let data = fileReader.result;
      console.log("FileREAAAAAAAAAAADER n" + data);
      this.parseData(data)
    }
    fileReader.readAsText(file);
  }

  parseData(data: string | ArrayBuffer | null){
    var dummyArr: string[][] = []
    var eachLine = data?.toString().split('n');
    eachLine?.forEach((line: string) => {
      let arr = []
      let str = ""
      for(var i = 0; i < line.length; i++){
        if(line[i] == ';'){
          arr.push(str)
          str = ""
        }else{
          str += line[i]
        }
      }
      arr.push(str)
      dummyArr.push(arr)
    })
    console.log(dummyArr);
  }


User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement