0

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?

1
  • please help me :) Commented Jul 4, 2021 at 17:00

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.