I'm appending data to a CSV file from a JSON rest API call. However, I'm finding whenever I write too it, it's adding the headers to the last item in the list.

My code is as follows
const csv = require('fast-csv')
const fs = require('fs')
const config = require('./config.json');
const date = new Date().getFullYear()
const filename = `${date}${config.filename}`;
async function createOrAppend(data) {
const fileExists = fs.existsSync(filename);
const writeStream = fs.createWriteStream(filename, { flags: fileExists ? 'a' : 'w' });
const csvStream = csv.format({ headers: true });
csvStream.pipe(writeStream);
// Write the data array to the CSV stream by looping through each item
if (fileExists) {
// If the file exists, we need to skip the header row
data.forEach(function(item){
csvStream.write(item, { headers: false });
})
} else {
// If the file does not exist, write the header row
data.forEach(function(item){
csvStream.write(item);
});
}
csvStream.end();
return new Promise((resolve, reject) => {
writeStream.on('finish', resolve);
writeStream.on('error', reject);
});
}
module.exports = {
createOrAppend
}
With the data coming in formatted as such
metrics.push({
region: region.region,
address: region.name,
vantagePoint: vantagePoint,
percentageHealthy: percentageHealthy.toFixed(2),
dateStart: dateStart.toISOString(),
dateEnd: dateEnd.toISOString()
});
fast-csvso what follows is speculation. 2) From here Formatting options: writeHeaders# Type: boolean Default: true Set to false you dont want to write headers. [...] This option can be used to append to an existing csv.headers: falseinstead ofwriteHeaders: false