0

I somehow can't get nodejs to put the results of a readline into the result variable. I guess it has something to do with readline being async? What would I have to do so I can save everything in a variable?.

var lineReader = require('readline').createInterface({
    input: require('fs').createReadStream('text.txt')
  });
var result = "Hello"; 

lineReader.on('line', function (line) {
  result += line;
});
console.log(result);
//result = "Hello"
R. Kohlisch
  • 2,823
  • 6
  • 29
  • 59
  • Thanks for this unhelpful reference to some massive thread. – R. Kohlisch Nov 15 '18 at 17:17
  • I'm sorry if it came across as unhelpful. Allow me to try and explain how it can help. `lineReader.on('line', ...` is an asynchronous operation. As you'll see in the linked question, you can't mix asynchronous and synchronous code in the way that you have. You need to handle it a little differently. In your case, consider adding a `lineReader.on('close', ...` event handler. – Mike Cluck Nov 15 '18 at 17:21
  • 1
    no worries, I was a bit frustrated, because I couldn't find anything that's concise, and then you linked to that super extensive answer :D fair enough though, i will go ahead and try what you suggest. thanks. – R. Kohlisch Nov 15 '18 at 18:37
  • Nah, I totally get what you mean. I'll try to check back at least a couple more times today just in case you hit some more snags. Good luck! – Mike Cluck Nov 15 '18 at 18:47

0 Answers0