csv-writer
csv-writer copied to clipboard
Append:true doesn't create a file with headers
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.
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 ?
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.
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,
})
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
]);
}