簡體   English   中英

csv-parse 是否允許您從文件中讀取?

[英]Does csv-parse allow you to read from file?

我正在學習如何為 nodejs 使用csv-parse模塊。 我寫了這段代碼,它完美地工作:

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是否有從文件讀取 f 的選項? 我問是因為正如您在我的代碼中看到的那樣,我必須指定自己line-break ,這在 csv 文件之間可能會有所不同。 我想也許csv-parse模塊可以更容易地解決這種情況?

解析器 object 將為您完成大部分工作。 它期望數據到達它的 stream 接口,它會做其他所有事情。 您所要做的就是向解析器打開 stream 和 pipe ,如下所示:

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

PS 令人驚訝的是,文檔中沒有顯示從文件中獲取 CSV 數據的這種簡單示例(至少在我能找到的任何地方都沒有)。 我也很驚訝,他們沒有提供自動從 stream 讀取數據的選項,而是要求您實現readable事件處理程序。 奇怪的是,對於這樣一個完整的 package。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM