2 回答
TA贡献1852条经验 获得超1个赞
首先,您必须拆分\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 链接: https: //repl.it/@h4shonline/ImpressionableRadiantLogic
TA贡献1898条经验 获得超8个赞
你为什么不:
逐行读取文件。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() {
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();
添加回答
举报