admin管理员组

文章数量:1332383

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.

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.

Share Improve this question edited Nov 17, 2014 at 14:42 Ben Fortune 32.1k10 gold badges81 silver badges81 bronze badges asked Nov 17, 2014 at 14:37 mandira goswamimandira goswami 511 silver badge5 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 4

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

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.

In case this may help somebody in the future: I experienced the same error and noticed that one of my rows contained a , -- resulting in fast csv throwing an error as it thought a new column was added. Resolved by escaping the 'cell' in quotation marks.

You can do this too:

csv
.fromStream(stream, {
    headers: true,
    strictColumnHandling: true
})
.validate(function(data) {
    if (data.age > 18)
        return false;
    else
        return true;
}
.on("data-invalid", function(data){
    // do something like log for example
});

本文标签: javascriptfastcsv is throwing exceptioncolumn header mismatch expectedStack Overflow