if you work with async functions you can wrap the call to csv-parser with a promise and then use await to wait for it to finish before moving to the next task.
Here is an example of how you do it:
const fs = require('fs');
const csv = require('csv-parser');
async function readCsv(csvFileName) {
function doParse(resolve) {
const results = [];
fs.createReadStream(csvFileName)
.pipe(csv())
.on('data', data=>results.push(data))
.on('end', () => {
resolve(results);
});
}
return new Promise((resolve) => doParse(resolve));
}
async function main(argv) {
console.log("BEGIN...\n");
let results = await readCsv(argv[2]);
for (let i = 0; i < results.length; ++i)
console.log(results[i]);
console.log("\n...END");
}
main(process.argv);
A simple way to "synchronously" parse a CSV file would be to wrap the parser code with a Promise to convert it to an async function then you can use await in order to wait for it to complete.
Here is a code example:
const fs = require('fs');
const csv = require('csv-parser');
async function readCsv(csvFileName) {
function doParse(resolve) {
const results = [];
fs.createReadStream(csvFileName)
.pipe(csv())
.on('data', data=>results.push(data))
.on('end', () => {
resolve(results);
});
}
return new Promise((resolve) => doParse(resolve));
}
async function main(argv) {
console.log("BEGIN...\n");
let results = await readCsv(argv[2]);
for (let i = 0; i < results.length; ++i)
console.log(results[i]);
console.log("\n...END");
}
main(process.argv);