Firstly, I assume that the file is a CSV, because of all the commas :).
You can easily parse CSV files with csv-parse.
We just need to additionally specify that the record_delimiter is a space (' '), not the standard new line ('\n')
const csv = require("csv-parse");
const fs = require('fs');
const res = [];
fs.createReadStream('test.txt')
.pipe(csv({ record_delimiter: ' '})) // pipe input stream to the CSV parser
.on('data', (data) => res.push(data)) // push data to the result array
.on('end', () => {
var price = 0; // create a variable for the price
for(var s=1; s<res.length; s++) // iterate over all records
price += parseInt(res[s][2]);
console.log(price); // print the price
})
.on('error', (err) => {
console.log("error: " + err);
});
We can also change it a bit so that we work with objects by setting columns to true (I find the data more sorted that way)
const csv = require("csv-parse");
const fs = require('fs');
const res = [];
fs.createReadStream('test.txt')
.pipe(csv({ record_delimiter: ' ', columns: true})) // pipe input stream to the CSV parser
.on('data', (data) => res.push(data)) // push data to the result array
.on('end', () => {
var price = 0; // create a variable for the price
res.forEach(el => price += parseInt(el.price)) // Iterate on each object and get the price field
console.log(price); // print the price
})
.on('error', (err) => {
console.log("error: " + err);
});
With this code the data looks like this:
[
{ id: '1', item: 'Milk', price: '5' },
{ id: '2', item: 'Soap', price: '10' },
{ id: '3', item: 'Water', price: '2' }
]