use*_*031 4 javascript csv json node.js npm-install
我想在现有的csv文件中添加新行?如果存在csv文件,那么我不想添加列标题,只想在文件中存在行之后添加新行.
这是我正在尝试的代码:
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);
}
});
Run Code Online (Sandbox Code Playgroud)
RLa*_*aaa 11
以下代码将执行您的要求:
之后的每次运行 - 将json数据附加到csv文件
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');
});
}
});
Run Code Online (Sandbox Code Playgroud)看来,最新版本json2csv有专门的方法来调用.parse()将 JSON 转换为 CSV 兼容字符串。我尝试了json2csv.parse()转换器,它对我有用。
我在此处给出的解决方案中发现了一个常见问题。HEADER如果我们多次运行该方法,解决方案不会附加数据。
我使用header提供的布尔选项来json2csv解决这个问题。如果我们使用{header:false}选项进行解析,我们将获得行数据。
// Rows without headers.
rows = json2csv(data, { header: false });
Run Code Online (Sandbox Code Playgroud)
下面是与我上面提到的完全一致的代码:
下面是代码示例:
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");
}
Run Code Online (Sandbox Code Playgroud)
Write功能我们有 3 个参数:
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'
}];
Run Code Online (Sandbox Code Playgroud)
现在调用该函数write:
write('test.csv', fields, data);
Run Code Online (Sandbox Code Playgroud)
每次我们调用上面的方法时,它都会从新行写入。如果文件不存在,它仅写入一次标头。
| 归档时间: |
|
| 查看次数: |
13573 次 |
| 最近记录: |