0

I've done some research over the last couple days and can't find a solution. I have this function which reads a csv file, parses the contents, separates the data and pushes into two separate arrays.

function formObjects(file) {
  fs.createReadStream(file)
    .pipe(csv())
    .on("data", (data) => results.push(data))
    .on("end", () => {
      results.forEach((item) => {
        //these arrays will be an array of strings until parsed
        if (item["Credit or Debit"] === "Credit") {
          let obj = {
            Description: item["Description"],
            Amount: parseInt(item["Amount"]),
          };
          credits.push(obj);
        }
        if (item["Credit or Debit"] === "Debit") {
          let obj = {
            Description: item["Description"],
            Amount: parseInt(item["Amount"]),
          };
          debits.push(obj);
        }
      });
      //return debits, credits <--- returns undefined
      console.log(debits);
      console.log(credits);
    });
}
formObjects("august.csv");

As said above, I can console.log(debits) and it prints the expected array of objects, but if I attempt to return the array to use in another function it is returning undefined. I have tried to add return credits.push(obj) and return debits.push(obj) to no avail. Hopefully someone can move me along here! Thanks!

Using npm module fs and csv-parser

Tres The Goat
  • 27
  • 1
  • 7
  • 1
    returning in a callback (`on('end', () => {` in this case) does not return a value from the outer function `formObjects` ... also, the values are logged in the console because console.log evaluates the arrays (in this case) when you view them .... if you were to `console.log(debits.length)` it would be ZERO at this point – Jaromanda X Sep 07 '20 at 03:46
  • @JaromandaX you are right. I did move my return line down to before the last curly bracket and it returns an empty array. – Tres The Goat Sep 07 '20 at 03:48
  • because asynchrony of the `on("end"` callback ... you'll need to use promises or a callback passed in to `formObjects` – Jaromanda X Sep 07 '20 at 03:49

0 Answers0