I've seen code examples of using csvtojson, but each one simply outputs the result using console.log(). The following code creates a variable named 'json', but I don't see how I can use this outside of the function creating it. How can I export the variable 'json' for use outside of the function that is creating it?:
const csvFilePath='<path to csv file>'
const csv=require('csvtojson')
csv().fromFile(csvFilePath,function(err,result){
if(err){
console.log("An Error Has Occured");
console.log(err);
}
var json = result; // I want to use this var outside of this function.
console.log(json);
});
I was really hoping that it would be as simple as writing something like:
const dataArray = csv().fromFile(csvFilePath);
But, dataArray doesn't contain my data, but instead appears to be an object with parameters about the data.
Any clues will be greatly appreciated!
I've learned a bit about async functions and promises since I posted this question. Since csvjson returns promises, I return the result of csv() to the next function in my chain:
const csv = require('csvtojson');
const filePath = '<path to csv file>';
// previous async function in promise chain
.then(() => {
return csv().fromFile(filePath)
})
.then(data => { // 'data' contains the json as converted by csv()
// next step in promise chain
})