Parsing a CSV file using NodeJS

后端 未结 16 2366
执笔经年
执笔经年 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:26

    • This solution uses csv-parser instead of csv-parse used in some of the answers above.
    • csv-parser came around 2 years after csv-parse.
    • Both of them solve the same purpose, but personally I have found csv-parser better, as it is easy to handle headers through it.

    Install the csv-parser first:

    npm install csv-parser
    

    So suppose you have a csv-file like this:

    NAME, AGE
    Lionel Messi, 31
    Andres Iniesta, 34
    

    You can perform the required operation as:

    const fs = require('fs'); 
    const csv = require('csv-parser');
    
    fs.createReadStream(inputFilePath)
    .pipe(csv())
    .on('data', function(data){
        try {
            console.log("Name is: "+data.NAME);
            console.log("Age is: "+data.AGE);
    
            //perform the operation
        }
        catch(err) {
            //error handler
        }
    })
    .on('end',function(){
        //some final operation
    });  
    

    For further reading refer

提交回复
热议问题