Search code examples
node.jscsvpapaparse

how to give file name a input in baby parser


I am trying to use baby parser for parsing csv file but i am getting below output if i give file name

file and code are in same directory

my code:

var Papa = require('babyparse');
var fs = require('fs');
var file = 'test.csv';
Papa.parse(file,{
    step: function(row){
        console.log("Row: ", row.data);
    }


});

Out put :

Row: [ [ 'test.csv' ] ]


Solution

  • file must be a File object: http://papaparse.com/docs#local-files. In nodejs, you should use the fs API to load the content of the file and then pass it to PapaParse: https://nodejs.org/api/fs.html#fs_fs_readfilesync_filename_options

    var Papa = require('babyparse');
    var fs = require('fs');
    var file = 'test.csv';
    
    var content = fs.readFileSync(file, { encoding: 'binary' });
    Papa.parse(content, {
        step: function(row){
            console.log("Row: ", row.data);
        }
    });
    

    The encoding option is important and setting it to binary works for any text/csv file, you could also set it to utf8 if your file is in unicode.