如何使用节点js将新列添加到csv文件 [英] How to add new column to csv file using node js
问题描述
我已经使用node.js npm软件包fast-csv尝试了此操作,但是没有解决方案,我可以成功读取csv文件,现在需要在现有的csv文件中添加新列.
I already tried this using node.js npm package fast-csv, but I don't get a solution, I can read csv file successfully, now I need to add a new column to my existing csv file.
我的问题:
如何在csv文件中添加新列?如何更新csv?
How to add new column to csv file? How to update csv?
var csv = require("fast-csv");
var fs = require('fs');
var stream = fs.createReadStream("file1.csv");
var service = 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=53.78943,-0.9985&destinations=53.540867,-0.510699&mode=driving&language=en-US';
var source = [];
var dest = [];
var distance = require('google-distance');
distance.apiKey = '************';
var i = 1;
csv
.fromStream(stream, { headers: true })
.on("data", function(data) {
//get source and distance array
source = data.SourceLatLong;
dest = data.DestBREPLatLong;
//print source and destinatoon
console.log(source);
console.log(dest);
distance.get({
// index: i,
origin: source,
destination: dest,
units: 'imperial'
},
function(err, map_data) {
if (err) return console.log(err);
//console.log(map_data);
//console miles of aff
console.log('source lat long ' + ':' + data.SourceLatLong + ' , ' + 'Dest lat long' + ':' + data.DestBREPLatLong + ',' + ' distance ' + ':' + map_data.distance + ' ' + i++);
});
})
.on("end", function() {
console.log("done");
});
在上面的程序中,我使用filecsv file1.csv,从中获取两列SourceLatLong
和DestLatLong
,并以英里为单位计算距离.现在,我需要在文件.csv
In the above program I use the filecsv file1.csv ,from i take two columns SourceLatLong
and DestLatLong
and I calculate distance in miles. Now I need to add new miles columns to my file .csv
推荐答案
使用csv-parser软件包而不是fast-csv,并使用json2csv将json解析为csv.
Use csv-parser package instead of fast-csv, and json2csv for json to csv parsing.
您要做的是使用csv-parser将csv的每一行转换为json,在结果json对象中添加一个新字段,针对每一行执行此操作,将结果放入数组中,将该数组转换为带有json2csv包的csv.
What you want to do is to convert each row of the csv to json using csv-parser, add a new field into the resulting json object, do this for each row, put the result in an array, convert that array into csv with json2csv package.
这是代码:
var csv = require('csv-parser');
var fs = require('fs');
var json2csv = require('json2csv');
var dataArray = [];
fs.createReadStream('your-original-csv-file.csv')
.pipe(csv())
.on('data', function (data) {
data.newColumn = newColumnValue;
dataArray.push(data);
})
.on('end', function(){
var result = json2csv({ data: dataArray, fields: Object.keys(dataArray[0]) });
fs.writeFileSync(fileName, result);
});
fs.writeFileSync仍然会覆盖原始文件,因此您也可以将其保存到原始csv文件中.
fs.writeFileSync overrides the original file anyway, so you can also save into the original csv file.
这篇关于如何使用节点js将新列添加到csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!