I am fresher in NodeJs and Javascript. Excuse me for trivial question. I am trying to read the file with the following piece of code and I want to read line by line and I want to populate to an array. I am able to print but I am not able to return the array with all the lines. I want to use NodeJs non-blocking api to read the file. Please help me know the problem in the following code.
public readFileLineByLineNonBlocking(fileNamePath: string): any {
        let allLines: string[] = [];
        const readLines = readline.createInterface({
            input: fs.createReadStream(fileNamePath),
            output: process.stdout,
            terminal: false
        });
        readLines.on('line', (line) => {
            allLines.push(line);
//            console.log(line); // Prints the line
        });
        // The following lines do not print
        allLines.forEach((line) => {
            console.log("IP Address: ", line);
        });
        return allLines;
    }
For testing, I write the following class. If you run the following class, you should see each line to be printed in the console.
import * as fs from "fs"; import readline from "readline";
class Test1 {
    public readFileLineByLineNonBlocking(fileNamePath: string): String[] {
        let allLines: string[] = [];
        const readLines = readline.createInterface({
            input: fs.createReadStream(fileNamePath),
            output: process.stdout,
            terminal: false
        });
        readLines.on('line', (line) => {
            allLines.push(line);
        }).on('close', () => {
            // allLines is fully populated here
            // this is where you can use the value
            allLines.forEach((line) => {
                // console.log("IP Address: ", line); // I do not want to print
            });
        }).on('error', err => {
            console.log(err);
        });
        return allLines;
    }
}
let test1 = new Test1();
const fileNamePath: string = "testData/ipaddress-50.txt";
let allLines: any = test1.readFileLineByLineNonBlocking(fileNamePath);
console.log("All Lines: ", allLines);// Coming as empty
 
    