问题
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);
}
});
回答1:
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, 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) { if (err) throw err; console.log('file saved'); }); } });
回答2:
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'}))
回答3:
using json-2-csv:
/**
* this function will create the file if not exists or append the
* data if exists
*/
function exportToCsvFile(headersArray, dataJsonArray, filename) {
converter.json2csvAsync(dataJsonArray, {prependHeader: false}).then(function (csv) {
fs.exists(filename + '.csv', async function (exists) {
if (!exists) {
var newLine = "\r\n";
var headers = ((headersArray ? headersArray : []) + newLine);
exists= await createFileAsync(filename+ '.csv', headers);
}
if (exists) {
fs.appendFile(filename + '.csv', csv, 'utf8', function (err) {
if (err) {
console.log('error csv file either not saved or corrupted file saved.');
} else {
console.log(filename + '.csv file appended successfully!');
}
});
}
});
}).catch(function (err) {
console.log("error while converting from json to csv: " + err);
return false;
});
}
function createFileAsync(filename, content) {
return new Promise(function (resolve, reject) {
fs.writeFile(filename, content, 'utf8', function (err) {
if (err) {
console.log('error '+filename +' file either not saved or corrupted file saved.');
resolve(0);
} else {
console.log(filename + ' file created successfully!');
resolve(1);
}
});
});
}
回答4:
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.
来源:https://stackoverflow.com/questions/40725959/how-to-append-new-row-in-exist-csv-file-in-nodejs-json2csv