Home > Enterprise >  Why does this code produce an empty dictionary and how can I fix it?
Why does this code produce an empty dictionary and how can I fix it?

Time:09-30

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);

CodePudding user response:

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.

  • Related