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