Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Read File and return count of certain lines

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;
        } 
    }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading