Array.push not saving using csvtojson

I’m using the csvtojson library to convert a csv to a json object and then push to an array. However, when I console.log(data) the array, it is empty but when I console.log(data) in csv({}) it does show the array with the jsonobj inside.

const csvFilePath = 'quotes.csv'; // Data
const headers = ['min', 'max', 'mode', 'sum', 'category']; 

let data = [], 

csv({noheader: true, headers: headers})
.fromFile(csvFilePath)
.then((jsonObj)=>{
    data.push(jsonObj)
    console.log(data);
})
console.log(data);

Thanks so much!

Hello there,

This looks like the case because the csv.fromFile method is asynchronous.

2 Likes

Now i feel silly. Wrote myself a CSV-JSON parser/lexer, to and from file… And the async stuff is a definite gotcha.

But yeah, data is being logged before the file has been read. Might be worth looking into Promises, or async/await.

1 Like

@Sky020 and @snowmonkey thanks so much for your help!
I see on the repo that there is
const jsonArray=await csv().fromFile(csvFilePath);
perhaps that could be of use (though I did get SyntaxError: await is only valid in async function error when I tried using it) so looks like I’ll have to add an async function and then can use it.

I tried adding an async/await function but I’m getting Promise { <pending> }

async function convertCsvToJson(csvData) {
    
    let jsonObj = await csv({noheader: true, headers: headers})
     .fromString(csvData);
     data.push(jsonObj)
    return jsonObj;
    
}
dat = convertCsv(csvFilePath)