Issue
I am trying to write one functionality where i am trying to read one csv file , and before that i am trying to check the headers of that perticular csv file are given correctly or not.Below is my code
let validHeaders = false;
fs.createReadStream(path)
.pipe(csv.parse({headers : true , ignoreEmpty : true}))
.on('headers',async function(headers){
validHeaders = await CustomValidation.isValidRowsExists(headers);
console.log(validHeaders); // here i am getting true
.on('data',async function(req,res,data){
console.log(validHeaders); //here i am getting false
if(validHeaders){ //do something
This is my CustomValidation class
class CustomValidation{
isValidRowsExists = async(csvRows) =>{
for(let i=0;i<csvRows.length;i++){
if(csvRows[0]==='Col1 && csvRows[1]==='Col2 ....){
return true;
}else{
return false;
}
}
}
}
module.exports = new CustomValidation;
How i can use the validHeaders value
Solution
Probably you need something like this:
const main = async () => {
const csvStream = fs
.createReadStream(path)
.pipe(csv.parse({ headers: true, ignoreEmpty: true }));
const validHeaders = await new Promise((resolve) =>
csvStream.on("headers", (headers) =>
resolve(CustomValidation.isValidRowsExists(headers))
)
);
csvStream.on("data", (data) => {
if (validHeaders) {
console.log(data);
}
});
};
main();
UPD:
A demo for Heiko with async validation
Answered By – moondef
Answer Checked By – Katrina (AngularFixing Volunteer)