Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

135
Visualizações
node.js is not updating the variable

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

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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 long validation demo

about 4 years ago · Juan Pablo Isaza Relatório

0

If CustomValidation.isValidRowsExists were asynchronous (but see below):

moondef's solution attaches the .on("data") handler only after awaiting result of CustomValidation.isValidRowsExists. But by then, the data events may already have happened.

I suggest to attach the handlers synchronously, and use a promise to log the data asynchronously, after the header validity has been determined.

var validHeaders;
csvStream.on("headers", function(headers) {
  validHeaders = Promise.resolve(CustomValidation.isValidRowsExists(headers));
})
.on("data", function(data) {
  validHeaders.then(function(valid) {
    if (valid) console.log(data);
  });
});

However, the CustomValidation.isValidRowsExists as shown is in reality not asynchronous, because it contains no await and does not return a promise.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda