0

I'm trying to read a file line by line using this:

function makeList() {
  let lines = [];
  var lineReader = require('readline').createInterface({
    input: require('fs').createReadStream('titles.txt')
  });
  lineReader.on('line', function(line) {
    //console.log(typeof line)
    lines.push(line);
    //console.log(lines)

  });
  return lines;
}

When enabling the comments I can see that the lines are read and are strings.

But when calling the function I always get an empty list:

async function run() {
  var p = makeList();
  console.log(p);
  for (line of lines) {
    console.log("Elaborando: " + line)
    for (let i = 1; i <= 18; i++) {

      if (!processString(line)) {

        fs.mkdirSync(processString(line));
      }
      await sleep(5000);
      //getImage(line, i, line);

    }
  }
}

run()

printing p to console gives an empty list. I'm not familiar with JavaScript, what am I doing wrong?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Tix00
  • 3
  • 1
  • its asynchronous, you are reading `p` before the elements are added to it – skara9 Jan 25 '22 at 14:11
  • where does `lines` come from in `run()`? The only other `lines` I see is local to `makeList()`. And then you don't even use `p`. – mykaf Jan 25 '22 at 14:13
  • What global variable are you referring to? `lines` is local to the `makeList` function; if you want the data, use `p`. However, you are trying to return the result of an asynchronous method, and therefore need to make the function asynchronous. – Heretic Monkey Jan 25 '22 at 14:13
  • Or, [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Heretic Monkey Jan 25 '22 at 14:14
  • "Lines" is what p used to be called. i changed it for debugging. Of course it gives an error, but the main problem is that 'p' is empty. I see that the Heretic Monkey links talks about my problem, but i still don't understand what should i change. Should i had an await? – Tix00 Jan 25 '22 at 14:46

0 Answers0