Home > other >  How to execute code after all rows of array has been read using Readline module
How to execute code after all rows of array has been read using Readline module

Time:11-26

I am trying to input an array of strings to my program using readline module. an example:

const readline = require('readline');
const r = readline.createInterface({
   input: process.stdin,
   output: process.stdout
});

var arr = [];

r.on('line', (line) => {
   arr.push(line)
   //code that run for every line
})

I want to execute code after all the lines in the array that i input are finished, is there an efficient way to do that? Or is there a way to check if the last line has been read?

sample array to be input:

arr = [
    'Maria Martinez',
    'James Johnson',
    'Maria Garcia',
    'David Smith'
]

CodePudding user response:

You need an event handler for the close event that will indicate when all the lines have been processed.

r.on('close', () => {
    // done processing all lines now
    console.log(arr);
});

And, probably should also be listening for the error event too.

  • Related