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

348
Visualizações
Why does this code produce an empty dictionary and how can I fix it?

I am trying to read a file and split on multiple characters. If I put the log statement within the rl.on block I get some outputs but for some reason the dictionary is empty again when the block is done.

let rl = readline.createInterface({
        input: fs.createReadStream('Spanish.txt'),
    })
    

   let dict={};
   let arr1=[];
   let arr2=[];
   rl.on(`line`, (line)=>{
       if (!line.startsWith('#')){
           arr1=line.split('\t');
           if (arr1[1]!=undefined) {
               arr2 = arr1[1].split('[').join(',').split('/').
               join(',').split('(').join(',').split(',');
               dict[arr1[0]]=arr2[0];
           }
       }
    });
    console.log(dict);

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

0

The lines are read asynchronously, so by the time you log your dict, processing has not yet completed.

You can listen for the close event to determine whether the file has been fully read:

rl.on('close', () => console.log(dict));

Better yet, use an async/await-based approach as detailed in the Node.js documentation.

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