javascriptnode.jscsvfast-csv

Add column to csv file javascript:nodejs


I would like to add a column to my csv file that contains the same data for all rows

my csv file :

sugar, 150, stock
salt, 30, stock
milk, 30, stockout

my file after adding the row (expected result):

product, sugar, 150, stock
product, salt, 30, stock
prouct, milk, 30, stockout

I want to add the field "product" to each line, my code :

const writestream = fs.createWriteStream("file.csv", {
  flags: 'a'
});
writestream.write("," + "product");

This returns product at the end of the file, How can i fix it

can I use the fast-csv library to add this field?


Solution

  • A similar question was asked here: How to add new column to csv file using node js. Long story short, use csv-parser to convert the csv to json, add your field, then convert that json back into csv with json2csv.

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

    This worked for me. The only problem is, I'm trying to loop that over multiple files I downloaded and renamed, it just doesn't save to all of them, only one.