I am attempting to read a CSV document and use its data to work out the cost of a sandwich. I am struggling as at first I was doing it as follows:
const entries = []
fs.createReadStream("./sandwiches.csv")
.pipe(parse({ delimiter: ",", from_line: 2 }))
.on("data", function (row) {
entries.push(new Sandwich(row[0], row[1]));
})
.on("end", function () {
return entries
})
.on("error", function (error) {
console.log(error.message);
});
I was attempting to store the returned entries but was not getting a value returned correctly, but it was logging the correct output to the console. I then saw that the below is the correct way to do it. However, I cannot store the below as variable, as I cannot use await at the top level. How do I get around this issue?
const fs = require("fs");
const { parse } = require("csv-parse");
const { finished } = require("stream/promises")
const storeSandwiches = async () => {
const entries = [];
const parser = fs
.createReadStream("./sandwiches.csv")
.pipe(parse({ delimiter: ",", from_line: 1 }));
parser
.on("readable", function () {
let record;
while ((record = parser.read()) !== null) {
entries.push(new Sandwich(record[0], record[1]));
}
})
// .on("end", function () {
// console.log("finished");
// })
.on("error", function (error) {
console.log(error.message);
});
await finished(parser);
return entries;
};
const sandwiches = await storeSandwiches()
Since the method
storeSandwiches
returns a promise and is an asynchronous operation, you need to fulfill the result by usingawait
orthen
.So your code would be changed to like this:
with await:
with then/catch:
read more about promise, here.