7

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.

readyready15728
  • 518
  • 3
  • 17

2 Answers2

10
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!

Community
  • 1
  • 1
Muntaser Ahmed
  • 4,487
  • 1
  • 16
  • 17
  • Now we're on to something from that linked question. Best practice for converting `fs.readFileSync('file.txt').toString().split("\n");` to stdin? – readyready15728 Jan 05 '17 at 01:47
  • It is still empty by using process.exit(0). I think the only ways are return a promise or use fs split?! – Weijing Jay Lin Apr 18 '18 at 18:49
  • 1
    Be careful, you cannot use the 'close' event signify that all the data has been processed. The line event can be called after the close event. – BeWarned Jan 06 '19 at 20:00
1

You'll want to access the lines array on close event:

var readline = require('readline');

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

var lines = [];

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

rl.on('close', () => {
  console.log(lines);
});

This code will establish the createInterface, and initialize an empty of array lines. At the prompt, when the user hits the enter key it fires the "line" event and adds the previous written line to the lines array. When you close the interface (by killing the process or manually closing in code) it will log out the array.

$ node readlines.js
this is
the second line
third
[ 'this is', 'the second line', 'third' ]
hackerrdave
  • 6,486
  • 1
  • 25
  • 29