【问题标题】:Does csv-parse allow you to read from file?csv-parse 是否允许您从文件中读取?
【发布时间】:2022-09-23 05:33:40
【问题描述】:

我正在学习如何将 csv-parse 模块用于 nodejs。我写了这段代码,它完美地工作:

var fs = require(\'fs\');
  
const fileName = \'./spreadsheet.csv\';
const assert = require(\'assert\');
const { parse } = require(\'csv-parse\');

const records = [];
// Initialize the parser
const parser = parse({
  delimiter: \',\'
});
// Use the readable stream api to consume records
parser.on(\'readable\', function(){
  let record;
  while ((record = parser.read()) !== null) {
    records.push(record);
  }
});
// Catch any error
parser.on(\'error\', function(err){
  console.error(err.message);
});


fs.readFile(fileName, \'utf8\', function (err, f) {
   if (err) {
      return console.error(err);
   }
   const rows = f.split(\"\\r\\n\");
   
   for(let x in rows) {
       parser.write(rows[x]+\"\\n\");
   }
   parser.end();

   console.log(records);
});

但现在,我依赖 fs 模块和 fs.readFile 来使用我的 csv 文件。 csv-parse 是否可以选择从文件中读取?我问是因为正如您在我的代码中看到的那样,我必须指定我自己的 line-break 字符,这在 csv 文件之间可能会有所不同。我想也许csv-parse 模块会有更容易解决这种情况的东西?

    标签: node.js node-csv-parse


    【解决方案1】:

    解析器对象将为您完成大部分工作。它期望数据到达它的流接口,它会做其他所有事情。您所要做的就是打开一个流并将其通过管道传输到解析器,如下所示:

    fs.createReadStream(fileName).pipe(parser);
    

    而且,在这里它与您的代码相结合:

    const fs = require('fs');
      
    const fileName = './spreadsheet.csv';
    const { parse } = require('csv-parse');
    
    const records = [];
    // Initialize the parser
    const parser = parse({
      delimiter: ','
    });
    // Use the readable stream api to consume records
    parser.on('readable', function(){
      let record;
      while ((record = parser.read()) !== null) {
        records.push(record);
      }
    });
    // Catch any error
    parser.on('error', function(err){
      console.error(err.message);
    });
    
    parser.on('end', function() {
        console.log(records);
    });
    
    // open the file and pipe it into the parser
    fs.createReadStream(fileName).pipe(parser);
    

    附言令人惊讶的是,文档中没有显示从文件中获取 CSV 数据的简单示例(至少在我能找到的任何地方都没有)。我也很惊讶,他们没有提供自动从流中读取数据的选项,而是要求您实现 readable 事件处理程序。奇怪,对于这样一个完整的包。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      相关资源
      最近更新 更多