user2848031 user2848031 - 16 days ago 16
JSON Question

How to append new row in exist csv file in nodejs json2csv?

I want to add new row in exist csv file? if csv file exist, then i don't want to add column header and just want to add new row after exist row in the file.

Here is code which I'm trying:

var fields = ['total', 'results[0].name.val'];
var fieldNames = ['Total', 'Name'];

var opts1 = {
data: data,
fields: fields,
fieldNames: fieldNames,
newLine: '\r\n'

};

var opts2 = {
newLine: '\r\n',
data: data,
fields: fields,
fieldNames: fieldNames,
hasCSVColumnTitle: false,

};

fs.stat('file.csv', function (err, stat) {
if (err == null) {
console.log('File exists');
var csv = json2csv(opts2);
fs.appendFile('file.csv', csv, function (err) {
if (err) throw err;
console.log('The "data to append" was appended to file!');
});
} else if (err.code == 'ENOENT') {
// file does not exist
var csv = json2csv(opts1);
fs.writeFile('file.csv', csv, function (err) {
if (err) throw err;
console.log('file saved');
});
} else {
console.log('Some other error: ', err.code);
}
});

Answer

The following code will do what you asked:

  1. When run the first time- will write the headers
  2. 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,
        hasCSVColumnTitle: 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, stat) {
                if (err) throw err;
                console.log('file saved');
            });
        }
    });