Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use readline in Node.js to get all input lines into an array?

I'd like to create a convenience function that does something like this for the purposes of CodeAbbey:

var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

var lines = [];

rl.on('line', (line) => {
  lines.push(line);
});

return lines;

However, because of how readline functions as an event handler of course all I get back is an empty array.

How do I get readline to carry out the desired behavior here? Or do I use some other library? I'd rather just use "default" components but if I have to use something else I will.

like image 656
readyready15728 Avatar asked Jan 05 '17 01:01

readyready15728


1 Answers

var lines = [];

rl.on('line', (line) => {
  lines.push(line);
}).on('close', () => {
  // Do what you need to do with lines here
  process.exit(0);
});

As Node.js runs on an event-loop, a lot of the functionality available in many packages, including Readline, are asynchronous. In general you will need to process lines when the close event is emitted.

You may find this very similar resolved question helpful: node.js: read a text file into an array. (Each line an item in the array.)

Hope this helps!

like image 132
Muntaser Ahmed Avatar answered Sep 24 '22 03:09

Muntaser Ahmed