Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fast-csv is throwing exception : column header mismatch expected

I am trying to validate data using fast-csv. My code looks like

var fileName = req.files.uploadcsv.path;
var fs = require("fs");

var stream = fs.createReadStream(fileName);

var csv = require("fast-csv");

csv
    .fromStream(stream, {
        headers: true
    })
    .validate(function(data) {
            if (data.age > 18)
                return false;
            else
                return true;

        }

    }

It works fine for every file I uploaded but if I uploaded file with extra data, it says Error: Unexpected Error: column header mismatch expected: 5 columns got: 6 Actually the file has 5 headers but data set it contains have 6 records. I want to catch this error so that I can point users to error.

Please suggest.

like image 481
mandira goswami Avatar asked Oct 24 '25 04:10

mandira goswami


2 Answers

SOLVED: This is because of the fast csv throwing an error as it thought a new column was added. so use discardUnmappedColumns option that throws away extra columns

 csv.fromStream(stream, {
    headers: true,
    discardUnmappedColumns: true
}).validate(function(data) {
        if (data.age > 18)
            return false;
        else
            return true;
    }
}
like image 81
GOVINDARAJ Avatar answered Oct 25 '25 18:10

GOVINDARAJ


I have solved it. Solution to the above problem is:

.on("error", function(data){
   return false;                         
 })

I have implemented this code after .validate() and it worked.

like image 34
mandira goswami Avatar answered Oct 25 '25 18:10

mandira goswami