0

I have a function that reads multiple json files. Now I want to modify it so that it can read csv files as well. I have another function that converts text into json arrays. I am trying to do this, but I am getting an error Property 'csvtoarray' does not exist on type 'FileReader'.ts(2339)

readFile(reader: FileReader, file: File) {
    const deferredResult = new Promise(resolve => {
      reader.addEventListener('load', function getResult() {
        console.log(file)
        if(file["type"] == "application/json"){
        resolve(reader.result as string)}
        else if(file["type"]=="text/csv"){
          resolve(this.csvtoarray(reader.result))
        }        
        reader.removeEventListener('load', getResult)
      })
    })

How can I call my function that converts text into json arrays in this readFile function?

My function that converts text into json arrays is:

csvtoarray(str,delimiter=','){
      const headers = str.slice(0,str.indexOf("\n")).split(delimiter)
      const rows = str.slice(str.indexOf("\n") + 1).split("\n")

      const arr = rows.map(function(row) {
        const values = row.split(delimiter);
        const el  = headers.reduce(function(object,header,index){
          object[header] = values[index];
          return object
        },{});
        return el
      });
      return arr
    }
harsh panday
  • 83
  • 1
  • 10
  • Can you just call `csvtoarray` directly? You shouldn't need `this.csvtoarray`. – bryce Jun 29 '22 at 20:45
  • @bryce I am working in Vue, so I need to do **this.csvtoarray** – harsh panday Jun 29 '22 at 20:51
  • The problem is that you're using a `function` for the `load` event handler, in which the `this` keyword will refer to the `FileReader` instance that fired the event. That instance doesn't have a `csvtoarray` method, as the error message shows - you'll need to call your class method. [Use an arrow function instead, or bind the function, or use `var that`, etc](https://stackoverflow.com/q/20279484/1048572). Or even better, use `deferredResult.then(this.csvtoarray)` instead of calling the method from within the event handler, so that the promise chain can handle exceptions. – Bergi Jun 29 '22 at 22:03

0 Answers0