Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

354
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!