0

let csv = require('fast-csv');
let fs = require('fs');
let readFileStream = fs.createReadStream(csvPath).setEncoding('utf-8');
let insList = [];
csv
    .fromStream(readStream, {headers: true})
    .on('data', function (data) {
        if (data[1] !== '' && insList.indexOf(data[1]) === -1 )
            insList.push(data[1]);

    })
    .on('end', function () {
        console.log(insList);
        console.log('done');
    })

The console.log(instList) line gives undefined when the {headers:true} is passed as argument to csv.fromStream. Why does that happen and how can I solve it?

If {headers:true} is not passed as argument the insList array gives the column name and all other unique elements in that column. I want the insList array to hold all unique items of column 1 (i.e. data[1]).

1 Answer 1

2

Edit 31-May-2022:

Sample working code in repl.it

Before 31-May-2022(works for an older version of fast-csv)

I have found that it works fine. However, the only problem was that the data is an object not an array. I have tested with this csv.

title,count
a,1
b,2


c,3
d,4

The data was an object in format { title: 'a', count:'1'}.

const csv = require('fast-csv');
const fs = require('fs');

const readStream = fs.createReadStream('./test.csv').setEncoding('utf-8');
const insList = [];
csv
  .fromStream(readStream, { headers: true, ignoreEmpty: true })
  .on('data', function (data) {
    console.log('data === ', data);
    // major change is here
    if (data && data !== {}) insList.push(data);
    else console.log('empty data', data);
  })
  .on('end', function () {
    console.log('end => ', insList);
    console.log('done');
  })

Hope this helps

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

2 Comments

what do you mean data is an object? my data is a csv file.
@ann I meant that the 'data variable' in callback is an object

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.