8

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.

My questions:

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");
});

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

Bhagvat Lande
  • 1,392
  • 3
  • 17
  • 34
  • I would suggest you to change API KEY and remove the one from your account and create a new one, if this API key is a functional one. Make sure you don't post real passwords, email, API keys on open site such as stackoverflow, they might be used for notorious purposes. – Surya Oct 21 '16 at 09:37
  • Do you want to make changes to the same file? Or is it okay to have the output in a new file? – Chaitanya Sama Oct 21 '16 at 10:23
  • thanku sir , appreciate yours answer – Bhagvat Lande Dec 05 '17 at 10:52

1 Answers1

14

Use csv-parser package instead of fast-csv, and json2csv for json to csv parsing.

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.

Here is the code:

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 overrides the original file anyway, so you can also save into the original csv file.

ardilgulez
  • 1,856
  • 18
  • 19