-
-
Notifications
You must be signed in to change notification settings - Fork 39
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
Comments
That is mention in documents
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:
|
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
]);
}
|
When there is no csv in the directory and setting
append
totrue
the headers don't get added to the top of the file prior to including the data.The text was updated successfully, but these errors were encountered: