How to append new row in exist csv file in nodejs json2csv?
Use csv-write-stream function to append data in csv file.
https://www.npmjs.com/package/csv-write-stream Add this line,with flag "a"
writer.pipe(fs.createWriteStream('out.csv', {flags: 'a'}))
Seems, latest version of json2csv
has dedicated method called .parse()
to convert JSON to CSV compatible string. I tried json2csv.parse()
converter and it works for me.
Common Issue:
I found a common issue in the solutions given here. The solutions don't append data without HEADER
if we run the method multiple times.
Solution:
I used the header
boolean option provided by json2csv
to fix the issue. If we parse with {header:false}
option we will get data as rows.
// Rows without headers.
rows = json2csv(data, { header: false });
Below is the code that works exactly I mentioned above:
Example Code:
Below is the code sample:
const fs = require('fs');
const path = require('path');
const json2csv = require('json2csv').parse;
const write = async (fileName, fields, data) => {
// output file in the same folder
const filename = path.join(__dirname, 'CSV', `${fileName}`);
let rows;
// If file doesn't exist, we will create new file and add rows with headers.
if (!fs.existsSync(filename)) {
rows = json2csv(data, { header: true });
} else {
// Rows without headers.
rows = json2csv(data, { header: false });
}
// Append file function can create new file too.
fs.appendFileSync(filename, rows);
// Always add new line if file already exists.
fs.appendFileSync(filename, "\r\n");
}
Calling Write
Function
We have 3 parameters:
fields = ['Name', 'Position', 'Salary'];
data = [{
'Name': 'Test1',
'Position': 'Manager',
'Salary': '$10500'
},
{
'Name': 'Test2',
'Position': 'Tester',
'Salary': '$5500'
}, {
'Name': 'Test3',
'Position': 'Developer',
'Salary': '$5500'
}, {
'Name': 'Test4',
'Position': 'Team Lead',
'Salary': '$7500'
}];
Now calling the function write
:
write('test.csv', fields, data);
Every time we call above method, it writes from a new line. It writes headers only once if file doesn't exist.
The following code will do what you asked:
- When run the first time- will write the headers
- Each run after that - will append json the data to the csv file
var fs = require('fs');
var json2csv = require('json2csv');
var newLine = '\r\n';
var fields = ['Total', 'Name'];
var appendThis = [
{
Total: '100',
Name: 'myName1',
},
{
Total: '200',
Name: 'myName2',
},
];
var toCsv = {
data: appendThis,
fields: fields,
header: false,
};
fs.stat('file.csv', function (err, stat) {
if (err == null) {
console.log('File exists');
//write the actual data and end with newline
var csv = json2csv(toCsv) + newLine;
fs.appendFile('file.csv', csv, function (err) {
if (err) throw err;
console.log('The "data to append" was appended to file!');
});
} else {
//write the headers and newline
console.log('New file, just writing headers');
fields = fields + newLine;
fs.writeFile('file.csv', fields, function (err) {
if (err) throw err;
console.log('file saved');
});
}
});