I have got a .txt files with few lines that contains numbers, such as
25 26 25 30
12 14 63 16
29 02 22 23
and I need to add all the numbers in the line, so the output in the console will be:
106
105
76
I am having difficulties to use readline to read the whole line and perform the calculation. using the example in https://nodejs.dev/learn/accept-input-from-the-command-line-in-nodejs
I can enter one line, and the calculation logic that I made was able to calculate the number, but only for one line and I have to manually enter the line in the console. Are there any way that I can get the readline to open the txt file instead and then it would read line by line and display all the addition to the console?
Thank you in advance
update:
what I have tried:
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();
CodePudding user response:
Read the .txt file value using
var fs = require('fs');
try {
var data = fs.readFileSync('file.txt', 'utf8');
console.log(data.toString());
} catch(e) {
console.log('Error:', e.stack);
}
Then take the .txt required value in a variable (input) and then try the below code snippet
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)
CodePudding user response:
I use the readline built in node.js modlue to read each line of the file. Otherwise you can also split the file with your OSes "EOL" delimiter.
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);
});
Simple split all values on a line into a array, convert the values to a actual JavaScript Number and calculate with a reduce the sum of all values.
https://nodejs.org/dist/latest-v16.x/docs/api/readline.html#readline