2 回答

TA貢獻1852條經(jīng)驗 獲得超1個贊
首先,您必須拆分\n文本文件中的新行 ( )。然后循環(huán)每一行并得到總數(shù):
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條經(jīng)驗 獲得超8個贊
你為什么不:
逐行讀取文件。https://nodejs.org/api/readline.html#readline_example_read_file_stream_line_by_line
刪除空格
用“:”分隔行
獲取最后一個元素
轉換為數(shù)字()
檢查它是否是一個數(shù)字
添加到總和
像這樣的東西:
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();
添加回答
舉報