Parsing a CSV file using NodeJS

后端 未结 16 2321
执笔经年
执笔经年 2020-11-27 12:15

With nodejs I want to parse a .csv file of 10000 records and do some operation on each row. I tried using http://www.adaltas.com/projects/node-csv. I couldnt get this to pau

16条回答
  •  独厮守ぢ
    2020-11-27 12:44

    I was using csv-parse but for larger files was running into performance issues one of the better libraries I have found is Papa Parse, docs are good, good support, lightweight, no dependencies.

    Install papaparse

    npm install papaparse
    

    Usage:

    • async / await
    const fs = require('fs');
    const Papa = require('papaparse');
    
    const csvFilePath = 'data/test.csv'
    
    // Function to read csv which returns a promise so you can do async / await.
    
    const readCSV = async (filePath) => {
      const csvFile = fs.readFileSync(filePath)
      const csvData = csvFile.toString()  
      return new Promise(resolve => {
        Papa.parse(csvData, {
          header: true,
          transformHeader: header => header.trim(),
          complete: results => {
            console.log('Complete', results.data.length, 'records.'); 
            resolve(results.data);
          }
        });
      });
    };
    
    const test = async () => {
      let parsedData = await readCSV(csvFilePath); 
    }
    
    test()
    
    • callback
    const fs = require('fs');
    const Papa = require('papaparse');
    
    const csvFilePath = 'data/test.csv'
    
    const file = fs.createReadStream(csvFilePath);
    
    var csvData=[];
    Papa.parse(file, {
      header: true,
      transformHeader: header => header.trim(),
      step: function(result) {
        csvData.push(result.data)
      },
      complete: function(results, file) {
        console.log('Complete', csvData.length, 'records.'); 
      }
    });
    

    Note header: true is an option on the config, see docs for other options

提交回复
热议问题