我如何使用node.js从txt文件中读取多行,然后对其进行计算?



我得到了一个.txt文件,其中包含几行数字,例如

25 26 25 30
12 14 63 16
29 02 22 23

和我需要添加行的所有数字,所以控制台的输出将是:

106
105
76

我很难使用readline读取整行并执行计算。使用中的示例https://nodejs.dev/learn/accept-input-from-the-command-line-in-nodejs

我可以输入一行,我所做的计算逻辑能够计算出数字,但只能计算一行,我必须手动在控制台中输入一行。有没有办法让readline打开文本文件,然后逐行读取,并在控制台显示所有附加内容?

提前谢谢你

更新:

what I have try:

const fs = require('fs');
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
})
const data = fs.readFileSync('./bin/numbers.txt')

let newData = data.split()
for(let datum of newData){
performCalc(datum); //this is the method to calculate the data;
console.log(`Total: ${sumOfNumbers} `);
}
readline.close();

使用

读取。txt文件值
var fs = require('fs');
try {  
var data = fs.readFileSync('file.txt', 'utf8');
console.log(data.toString());    
} catch(e) {
console.log('Error:', e.stack);
}

然后在变量(输入)中获取.txt所需的值,然后尝试下面的代码片段

const input = `25 26 25 30
12 14 63 16
29 02 22 23`
const result = input.split(/r?n/).map(element=>{
return element.split(" ").map(el=> Number(el)).reduce((a,b) => a+b ,0)
})
console.log(result)

我使用node.js模块内置的readline读取文件的每行。否则,你也可以用你的操作系统拆分文件。分隔符。

const fs = require("fs");
const readline = require("readline");
// read the file as input stream
// let the readline module do the line parsing
const rl = readline.createInterface({
input: fs.createReadStream("input.txt")
});

rl.on("line", (input) => {
// split the values by space & convert them to a number
// calculate the sum of all values in the array with a reduce
let sum = input.split(" ").map(v => Number(v)).reduce((prev, cur) => {
return prev + cur;
}, 0);
console.log(`Sum of input (${input})`, sum);
});

简单地将一行中的所有值拆分为数组,将值转换为实际的JavaScript Number,并使用reduce计算所有值的总和。

https://nodejs.org/dist/latest-v16.x/docs/api/readline.html readline

最新更新