Reputation: 66
Just trying to experiment with node and lost on this one.
I am trying to read a file using node.js and sum the prices in that file.
So far I can read the data but am having problems adding just the prices.
const fs = require('fs')
fs.readFile('file.txt', 'utf8' , (err, data) => {
if (err) {
console.error(err)
return
}
console.log(data)
})
in file.txt I have
"id,item,price 1,Milk,5 2,Soap,10 3,Water,2"
From the file.txt I only need to add the prices and print it out.
For example for above example, I would have "price = 17"
Any guidance in the right direction is appreciated
Upvotes: 0
Views: 1510
Reputation: 114
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' }
]
Upvotes: 1