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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With