Search code examples
javascriptnode.jsreadfilereadline

Save array made with readline module


I have the next piece of code. It's a function that has to return an array based on a txt file. The problem is when I print piece by piece the array, it prints well. But when I print the array out of the Interface, the array is empty.

const fs = require('fs');
const readline = require('readline');

function read_file(filename) {
   const filePath = './uploads/' + filename;
   var data = []

   data = readline.createInterface({
      input: fs.createReadStream(filePath),
      terminal: false
   }).on('line', function (
      data.push(line);
      console.log(data); // Here the array is filling well
   });

   console.log(data); // Buy here is empty again
}


Solution

  • It's because of an asynchronous architecture of Node.js, your console.log executes before read file task.

    If you wanna expect a true result, you must make your function to return promise, and also notice that when your event finish then resolve your data.

    Something like this might help you:

    const fs = require('fs');
    const readline = require('readline');
    
    async function read_file(filename) {
      const filePath = './uploads/' + filename;
      var readData = [];
    
      let data = await new Promise((resolve, reject) => {
        try {
          readline.createInterface({
            input: fs.createReadStream(filePath),
            terminal: false
          })
            .on('line', function (line) {
              readData.push(line);
            })
            .on('close', function() {
              resolve(readData);
            });
          }
          catch(e) {
           reject(e);
          }
       });
    
     console.log(data);
    }