I'm currently trying to pull json data from and API, convert it to csv using the json2csv node.js module, and then save the data as a csv file on my laptop. However, when I run the script, nothing happens.
The json data is then formatted similar to the below data variable:
const apiDataPull = postDataRequest()
.then(data => {
data = [
{
'day': '*date*',
'revenue': '*revenue value*'
}
]
And this is to convert the data to csv and download it, which is where the problem seems to be arising:
apiDataPull.then(data => {
json2csv({
data: data,
fields: ['day', 'revenue', 'totalImpressions', 'eCPM']
},
function(err, csv) {
if (err) console.log(err);
fs.writeFile('pubmaticData.csv', csv, function(err){
if (err) throw err;
console.log('File Saved!')
});
});
});
There is data being pulled from the API, but it's not being saved. I'm not even sure if it's been converted to csv properly or not.
You are probably not starting the promises, and it looks like you are not using the json2csv correctly.
Take a look at this example:
let json2csv = require("json2csv");
let fs = require("fs");
apiDataPull = Promise.resolve([
{
'day': '*date*',
'revenue': '*revenue value*'
}]).then(data => {
return json2csv.parseAsync(data, {fields: ['day', 'revenue', 'totalImpressions', 'eCPM']})
}).then(csv => {
fs.writeFile('pubmaticData.csv', csv, function (err) {
if (err) throw err;
console.log('File Saved!')
});
});
The saved file is:
"day","revenue","totalImpressions","eCPM"
"*date*","*revenue value*",,