1

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. enter image description here

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()
  });
2
  • 3
    1) I don't use fast-csv so 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. Commented Aug 12 at 14:57
  • Per above, this looks like you have a typo: headers: false instead of writeHeaders: false Commented Aug 13 at 4:32

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.