Trying to return 2D-array with fast-csv in Nodejs but returning none

Viewed 528

I am attempting to parse a csv-file using fast-csv library and convert each values number or string to create 2d array. But I can't return array in ReadStream. Can you give me advice on my code?

const fs = require("fs");
const csv = require("fast-csv");

async csvParse(){

  let array = [];
  
  options = {
    map(value){
      // convert value's column type to number or string
    }
  }

  fs.createReadStream(csvfile)
      .pipe(csv.parse(options))
      .on("error", error => console.log(error))
      .on("data", data => array.push(data))
      .on("end", function(){
         console.log(array);
         return array;
      })
}

input

name,date,score,id
John,2020-01-01,1000,10

expected-output

[["name", "date", "score", "id"], ["John", "2020-01-01", 1000, 10]]

actual-output

// no output

I expect the code to return "expected-output" that converted from "input", but it returns none. I understand this is due to me attempting to return a value from the anonymous function on(), however I do not know the proper approach.

1 Answers

You can wrap processing of the file-stream and the csv-conversion in a promise and resolve the promise once the end-event is emitted:

const fs = require("fs");
const csv = require("fast-csv");

function csvParse() {

    const options = {
        // your options here
    }
    let array = [];
    return new Promise((resolve, reject) => {
        fs.createReadStream(csvfile)
        .pipe(csv.parse(options))
        .on("error", error => reject(error))
        .on("data", data => array.push(data))
        .on("end", () => {
            console.log(array);
            resolve(array);
        });
    });

}

Then call it like this:

(async() => {
    const result = await csvParse();
})();
Related