csv-writer icon indicating copy to clipboard operation
csv-writer copied to clipboard

Append:true doesn't create a file with headers

Open peterpoliwoda opened this issue 3 years ago • 4 comments

When there is no csv in the directory and setting append to true the headers don't get added to the top of the file prior to including the data.

peterpoliwoda avatar Oct 26 '21 21:10 peterpoliwoda

That is mention in documents

append (optional) Default: false. When true, it will append CSV records to the specified file. If the file doesn't exist, it will create one. NOTE: A header line will not be written to the file if true is given.

But is there any work around ?

artur-dani avatar Sep 19 '22 15:09 artur-dani

I may come a little late, but what I did was check if the file I was about to write in was empty. If it was, I wrote the first line of data with the name of every header's field.

danifm1321 avatar Jan 17 '23 20:01 danifm1321

The following can be used as workaround:

    const header = {id: name, title: name};
    const path = `/my/path`;
    let append = false;

    try {
        await fs.access(path);
        const st = await fs.stat(path);
        append = st.size > 0;
    } catch (e) { }

    const csvWriter = createObjectCsvWriter({
        path,
        append,
        header,
    })

mbitto avatar May 27 '23 20:05 mbitto

I built off of mbitto's code and landed on this to dynamically set the append flag based on the existence of the output file:

const fs = require('fs').promises;
const path = require('path')

const createCsvWriter = require('csv-writer').createObjectCsvWriter;

const outputDirPath = path.resolve(__dirname, 'output')
const outputFilePath = path.join(outputDirPath, 'file.csv')

const header = [
  { id: 'date', title: 'DATE' },
  // ... your headers
];

async function createCsvWriterWithHeader() {
  let append = false

  try {
    await fs.access(outputFilePath);
    const st = await fs.stat(outputFilePath);
    append = st.size > 0;
  } catch (e) {
    // If the file doesn't exist or can't be accessed, we'll create a new one with headers
  }

  return createCsvWriter({
    path: outputFilePath,
    append,
    header,
  });

async function appendToCsv(metrics) {
  const csvWriter = await createCsvWriterWithHeader(); // Wait for the CSV writer to be configured
  await csvWriter.writeRecords([
    // your records
  ]);
}


jonchurch avatar Nov 06 '23 23:11 jonchurch