3

With reactjs (in Meteor) I would like to read a local csv file with a relative path and loop over it's rows:

import Papa from 'papaparse';
var csvfile = "../../../data.csv";
Papa.parse(csvfile, {
  step: function (row) {
    console.log("Row:", row.data);
  },
});

This returns

Row: [ [ '../../../data.csv' ] ]

Joost Döbken
  • 3,450
  • 2
  • 35
  • 79

3 Answers3

4

You can set the download config flag when using a file instead of a string as input. From the config documentation:

If true, this indicates that the string you passed as the first argument to parse() is actually a URL from which to download a file and parse its contents.

import csvFile from '../../data/my-csv-file.csv'

Papa.parse(csvFile, {
    download: true,
    complete: function (input) {
         const records = input.data;
    }
});
Simon Raes
  • 442
  • 4
  • 15
3

Simon Raes' answer helped the most. Here's a complete React example:

import React from 'react';
import { readString } from 'react-papaparse';
import siteListCSV from './example.csv';

const papaConfig = {
  complete: (results, file) => {
    console.log('Parsing complete:', results, file);
  },
  download: true,
  error: (error, file) => {
    console.log('Error while parsing:', error, file);
  },
};
readString(siteListCSV, papaConfig);

function App() {
  return (
    <h1>Check the console</h1>
  );
}

export default App;
LoopDuplicate
  • 453
  • 5
  • 7
  • This gives me a "unable to resolve module error" on the "import siteListCSV from './example.csv' " and says none of the files exist, even though my file is there. Thanks for the help – willheard27 Feb 05 '23 at 04:41
0

Looks like your library expect JSON, whereas you specified a path.

You should read the JSON from your file using fs and then pass that to the parse method.

fs.readFile(csvFile, 'utf8', function (err, data) {
    if (err) {
        throw err;
    }
    Papa.parse(data, {
     step: function (row) {
      console.log("Row:", row.data);
     }
   });
});
Joost Döbken
  • 3,450
  • 2
  • 35
  • 79
paqash
  • 2,294
  • 1
  • 17
  • 22