I am trying to create a CSV. Since the data is huge, I wanted to keep appending the data into the file rather than first storing the records in an array and then dumping all the data at once into the CSV. So I wrote the following code, that simulates what I want to do. 50 random records are created and appended to the file each second. The code works fine, but the problem is the final CSV. It looks like the following:
"id","value""value","id"
3226,"3653aab688be4934""value","id"
4070,"9de2be11958fa207""value","id"
2061,"b754b9164146d37f""value","id"
6216,"ac85aa653bfc845d""value","id"
48,"caf5f55c49fde7bf""value","id"
4330,"2c33ae658de7a3eb""value","id"
1997,"34caef7b4ae96edd""value","id"
I could not understand the reason for this. I also read the related SO post but that did not help either.
const json2csv = require('json2csv').parse;
const fs = require('fs');
Promise = require('bluebird');
let plist = [];
let count = 0;
let intvl = null;
let fields = ['id', 'value'];
function start() {
if(count++ > 50) {
Promise.all(plist)
.then(r => {
clearInterval(intvl);
console.log('file created');
process.exit(0);
})
.catch(err => {
console.log(err);
process.exit(-1);
})
}
let data = [{
value: Math.floor(Math.random() * 9999),
id: require('crypto').randomBytes(8).toString('hex')
}];
plist.push(append(json2csv(data)));
}
function append(data) {
return new Promise((resolve, reject) => {
fs.appendFile('./stream.csv', data, (err, resp) => {
if(err) reject(err);
else resolve();
});
});
}
function init() {
fs.stat('./stream.csv', (err, resp) => {
if(err) {
fs.writeFileSync('./stream.csv', json2csv([], {fields}));
}
intvl = setInterval(() => {
start();
}, 1100);
})
}
init();
What is it that I am missing? Initially, the code checks if the file already exists. If it does not, creates the file with just headers and then the regular write process follows. I tried removing the part where only headers are written. It helps in removing the duplicate headers at the top but does not help the repitition of headers in each row. How could that be prevented?