从文件 Nodejs 解析数据

时间:2021-03-12 18:34:18

标签: node.js

只是尝试使用 node 并在这个节点上失败了。

我正在尝试使用 node.js 读取文件并对该文件中的价格求和。

到目前为止,我可以读取数据,但在添加价格时遇到问题。

const fs = require('fs')

fs.readFile('file.txt', 'utf8' , (err, data) => {
  if (err) {
    console.error(err)
    return
  }
  console.log(data)
})

在 file.txt 我有

<块引用>

"id,item,price 1,牛奶,5 2,肥皂,10 3,水,2"

从 file.txt 我只需要添加价格并打印出来。

例如上面的例子,我会有“price = 17”

感谢任何正确方向的指导

1 个答案:

答案 0 :(得分:1)

首先,我假设文件是​​一个 CSV,因为所有的逗号:)

您可以使用 csv-parse 轻松解析 CSV 文件。

我们只需要另外指定 record_delimiter 是一个空格 (' '),而不是标准的换行符 ('\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);
    });

我们也可以稍微改变它,以便我们通过将 columns 设置为 true 来处理对象(我发现这样的数据更排序)

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);
    });

使用此代码,数据如下所示:

[
  { id: '1', item: 'Milk', price: '5' },
  { id: '2', item: 'Soap', price: '10' },
  { id: '3', item: 'Water', price: '2' }
]
相关问题