3

I am trying to write a simple node program that reads a csv file, extracts a column (say second) and writes it to another CSV file. I am reading the contents to an array and then writing that array to file.

Stages and data in each step

inputfile

123,456,789,abc
def,ghi,232,jkl

array

['456','ghi']

outputfile

4,5,6
g,h,i

output needed

456
ghi

Am i just missing a configuration or is the way i am writing data wrong? Is my block of code to write to file within END block not correct?

Here is my code

var fast_csv = require('fast-csv');
var tempArray=new Array();
console.log("START");
fast_csv.fromPath("inputfile.txt").on("data", function(data){
    tempArray.push(data[1]);  
})
  .on("end", function(){
    tempArray.sort();
    console.log(tempArray);

    fast_csv.writeToPath("outputfile.csv", tempArray)
   .on("finish", function(){
      console.log("END");
   });

}); 
2
  • any suggestions ? Commented Oct 9, 2016 at 3:52
  • Their examples are trash Commented Jan 14, 2022 at 10:02

2 Answers 2

4

It treats each element in the array as an array, so '456' is treated as an array with the elements 4,5,6.

A strange workaround I did was to loop through the array and put each element inside its own array, so it would be:

var newArray = [];

 for( var i = 0; i < tempArray.length; i++){
 var arr = [];
 arr.push(tempArray[i]);
newArray.push(arr);
}

And then write the "newArray".

But otherwise if you write row by row, you can put each element inside a bracket, like:

var fast_csv = fastcsv.createWriteStream();
var writeStream = fs.createWriteStream("outputfile.csv");
fast_csv.pipe(writeStream);

for(var i = 0; i < tempArray.length; i++){
    fast_csv.write( [ tempArray[i]  ] );             //each element inside bracket
    }
fast_csv.end();
Sign up to request clarification or add additional context in comments.

Comments

1

Change: tempArray.push(data[1]); to: tempArray.push([data[1]]);

writeToPath takes an array of arrays.

Docs: https://www.npmjs.com/package/fast-csv

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.