0

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

1 Answer 1

1

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' }
]
Sign up to request clarification or add additional context in comments.

2 Comments

Not sure if the solution is correct as I am getting 0 and my file is .txt not .csv
Yeah, I just noticed that there are " at the start and end of the file, if you remove those, it should be fine. Also, it is not a problem that the extension is .txt and not .csv

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.