【问题标题】:node js Filter CSV Row based on Column Contentnode js根据列内容过滤CSV行
【发布时间】:2020-05-25 04:33:07
【问题描述】:

我正在尝试在加载时过滤一个 CSV 文件,目前已获得以下信息:

const csv = require('csv-parser');
const fs = require('fs');

fs.createReadStream('Names.csv')
  .pipe(csv())
  .on('data', (row) => {
      // If Column 2 Is 6
      // If Column 3 is Y
    console.log(row);
  })
  .on('end', () => {
    console.log('CSV file successfully processed');
  });

如果到处寻找参考/起点但没有取得太大进展。

【问题讨论】:

    标签: node.js node-csv-parse


    【解决方案1】:

    您需要使用回调来获取过滤行的结果:

    const csv = require('csv-parser');
    const fs = require('fs');
    function getFilteredData(y, callback){ 
        const result = [];                 
        fs.createReadStream('Names.csv')
          .pipe(csv())
          .on('data', (row) => {
              const headers = Object.keys(row);
              if(Number(row[headers[1]]) === 6 && row[headers[2]] === y )
                  result.push(row)
           })
          .on('end', () => {
              console.log('CSV file successfully processed');
              callback(result)
           });
    }
    

    或者如果你想把它作为一个流,你需要编写一个转换流或一个双工流

    【讨论】:

    • 感觉像是朝着正确方向迈出的一步。如果我用 console.log(row[1]) 替换 If 语句,则输出为 'Undefined'
    猜你喜欢
    • 2021-05-17
    • 1970-01-01
    • 2011-01-10
    • 2012-07-03
    • 2021-09-04
    • 2020-10-05
    • 2019-10-01
    • 2014-02-21
    • 1970-01-01
    相关资源
    最近更新 更多