我在 NodeJS 中遇到有关文件处理的问题

I have a problem in NodeJS about file handling

我无法解决 NodeJS:I 中的以下文件处理问题有一个文件 emp.txt 包含以下格式的固定记录大小的员工数据:

    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

我已尝试使用以下代码成功读取文件,但没有找到解决确切问题的逻辑。我读取文件的代码:

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

emp.txt 读取 Salary 字段并计算其总和的正确逻辑是什么?

首先,您必须在文本文件中拆分新行 (\n)。然后遍历每一行并得到总数:

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

你为什么不:

像这样:

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();