I have a problem in NodeJS about file handling

Viewed 143

I'm not able to solve following file Handling problem in NodeJS:I have a file emp.txt that contains employee data in fixed record size in the following format:

    EmpID:Name:Dept:Salary
    1001:Harry:Sales:23000
    1002:Sarita:Accounts:20000
    1003:Monika:TechSupport:35000
    Read the file. Display sum of salary of all employees

I have tried following code to read file successfully, but not getting logic to solve the exact problem. My code to read File:

    var fs = require("fs");
    console.log("Going to read file!");

    fs.readFile('emp.txt', function(err, data){
        if(err){
            return console.error(err);
        }
        console.log(data.toString().split(":"));
        console.log("read Successfully");
    })

What is the correct logic to read Salary field from emp.txt and calculate it's sum?

2 Answers

First you have to split the new lines (\n) in your text file. Then loop through each row and get the total:

var fs = require("fs");
console.log("Going to read file!");

let totalSalary = 0;
fs.readFile('emp.txt', function(err, data){
    if(err){
        return console.error(err);
    }
    const dataRows = data.toString().split("\n");
    for (let index=0;  index < dataRows.length; index++){
      if (index > 0){
        let empData = dataRows[index].split(":");
        totalSalary += parseInt(empData[3]);
      }
    }

    console.log(totalSalary);

    console.log("read Successfully");
})

Repl.it Link : https://repl.it/@h4shonline/ImpressionableRadiantLogic

Why dont you:

Something like this:

const fs = require('fs');
const readline = require('readline');

async function processLineByLine() {
    const fileStream = fs.createReadStream('emp.txt');
  
    const rl = readline.createInterface({
      input: fileStream,
      crlfDelay: Infinity
    });
    // Note: we use the crlfDelay option to recognize all instances of CR LF
    // ('\r\n') in input.txt as a single line break.
    let sum = 0;
    for await (let line of rl) {
      // Each line in input.txt will be successively available here as `line`.
      line = line.replace(/ /g,'').split(':');
      const salary = Number(line.pop());
      if (!isNaN(salary)) {
        sum += salary;
      }
    }
    console.log(`Sum: ${sum}`)
  }

  processLineByLine();
Related