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

我无法解决 NodeJS 中的以下文件处理问题:我有一个文件 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");

    })

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


一只斗牛犬
浏览 95回答 2
2回答

小怪兽爱吃肉

首先,您必须拆分\n文本文件中的新行 ( )。然后循环每一行并得到总数:var fs = require("fs");console.log("Going to read file!");let totalSalary = 0;fs.readFile('emp.txt', function(err, data){&nbsp; &nbsp; if(err){&nbsp; &nbsp; &nbsp; &nbsp; return console.error(err);&nbsp; &nbsp; }&nbsp; &nbsp; const dataRows = data.toString().split("\n");&nbsp; &nbsp; for (let index=0;&nbsp; index < dataRows.length; index++){&nbsp; &nbsp; &nbsp; if (index > 0){&nbsp; &nbsp; &nbsp; &nbsp; let empData = dataRows[index].split(":");&nbsp; &nbsp; &nbsp; &nbsp; totalSalary += parseInt(empData[3]);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; console.log(totalSalary);&nbsp; &nbsp; console.log("read Successfully");})Repl.it 链接: https: //repl.it/@h4shonline/ImpressionableRadiantLogic

汪汪一只猫

你为什么不:逐行读取文件。https://nodejs.org/api/readline.html#readline_example_read_file_stream_line_by_line删除空格用“:”分隔行获取最后一个元素转换为数字()检查它是否是一个数字添加到总和像这样的东西:const fs = require('fs');const readline = require('readline');async function processLineByLine() {&nbsp; &nbsp; const fileStream = fs.createReadStream('emp.txt');&nbsp;&nbsp;&nbsp; &nbsp; const rl = readline.createInterface({&nbsp; &nbsp; &nbsp; input: fileStream,&nbsp; &nbsp; &nbsp; crlfDelay: Infinity&nbsp; &nbsp; });&nbsp; &nbsp; // Note: we use the crlfDelay option to recognize all instances of CR LF&nbsp; &nbsp; // ('\r\n') in input.txt as a single line break.&nbsp; &nbsp; let sum = 0;&nbsp; &nbsp; for await (let line of rl) {&nbsp; &nbsp; &nbsp; // Each line in input.txt will be successively available here as `line`.&nbsp; &nbsp; &nbsp; line = line.replace(/ /g,'').split(':');&nbsp; &nbsp; &nbsp; const salary = Number(line.pop());&nbsp; &nbsp; &nbsp; if (!isNaN(salary)) {&nbsp; &nbsp; &nbsp; &nbsp; sum += salary;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; console.log(`Sum: ${sum}`)&nbsp; }&nbsp; processLineByLine();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript