Home > Mobile >  Read File and return count of certain lines
Read File and return count of certain lines

Time:04-01

I am attempting to read a flat (text) file and return the number of lines that start with a "1" or a "2".

The issue i'm seeing is that the "recordCount" returns a 0. Would like the recordCount variable to be incremented by 1 every time the condition is met.

export async function getReportRecordCount(finalFile: string, filePath: string) {
    try {
        let recordCount = 0;
        const rl = readline.createInterface({
            input: fs.createReadStream(`${filePath}/${finalFile}`),
            output: process.stdout
        });
        rl.on("line", (line) => {
            if (line.toString().startsWith("1" || "2")) {
                recordCount  ;
            }
        });
        return recordCount;
        } 
    }

CodePudding user response:

You need to properly promisify the getReportRecordCount function (right now, it's returning recordCount immediately, right after the interface is created, before any of the lines have been read. In order to listen for all lines to have finished being read, use the close event.

You also need to fix the startsWith logic - ("1" || "2") evaluates to "1". Use a regular expression instead.

export function getReportRecordCount(finalFile: string, filePath: string) {
    return new Promise((resolve, reject) => {
        let recordCount = 0;
        const rl = readline.createInterface({
            input: fs.createReadStream(`${filePath}/${finalFile}`),
            output: process.stdout
        });
        rl.on("line", (line) => {
            if (/^[12]/.test(line.toString())) {
                recordCount  ;
            }
        });
        r1.on("error", reject);
        r1.on("close", () => resolve(recordCount));
    });
}

Once it becomes more stable, I'd suggest using readline's Promises API instead of manually constructing the Promise.

  • Related