Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Append:true doesn't create a file with headers #81

Open
peterpoliwoda opened this issue Oct 26, 2021 · 4 comments
Open

Append:true doesn't create a file with headers #81

peterpoliwoda opened this issue Oct 26, 2021 · 4 comments

Comments

@peterpoliwoda
Copy link

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.

@artur-dani
Copy link

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 ?

@danifm1321
Copy link

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.

@mbitto
Copy link

mbitto commented May 27, 2023

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,
    })

@jonchurch
Copy link

jonchurch commented Nov 6, 2023

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
  ]);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants