0

I am working in ReactJS, my app is currently running locally with Create React App. I have a .csv file in my project src folder that I need to read in and convert to an array of javascript objects using Papaparse, but can't figure out how to create a File object to pass into the Papa.parse() method. The File documentation seems to all refer to creating a new file or reading a file passed by a user through drag and drop, etc. I can't find a reference to creating a File by pathname. I was previously successfully reading a json file stored in the same place in the src folder, but now need to switch to reading csv and converting to array of JS objects. There is no problem with the formatting of the .csv, I copied several lines of it as a multiline string and it was correctly parsed to json with Papa.parse(), but I don't understand how to pass in a File.

1
  • Please provide enough code so others can better understand or reproduce the problem. Commented Apr 4, 2022 at 17:54

1 Answer 1

1

You are dealing with data on your server, not data the user is picking from a file <input>. Use URLs, not File objects.

You need to give the CSV file a URL (how you do that depends on the particular server you are using, this question seems to cover it if you are using the Webpack development server).

Then you need to pass that URL a per the documentation to Papa Parse.

Papa.parse("http://example.com/file.csv", {
    download: true,
    complete: function(results) {
        console.log(results);
    }
});
Sign up to request clarification or add additional context in comments.

6 Comments

Why is it not possible to access by filename? The data is private and cannot be publicly available by url. With .json file, I was able to import directly with const data = require('../../../data.json'); is there no parallel way to do this with .csv?
"Why is it not possible to access by filename?" — Because it would be a major security problem if a web browser could go to a website and then access any file on the server's disk.
"The data is private and cannot be publicly available by url." — You can't give the data to the browser without giving the data to the browser. URLs are used for that purpose. Put password protection (or similar) on it if you want to restrict who can access it.
"With .json file, I was able to import directly with const data = require('../../../data.json');" — Webpack can bundle JSON files. It still sends the data to the browser and makes it public.
"Is there no parallel way to do this with .csv?" — I'm sure there's a -loader module for Webpack which can handle generic files and give you a string. It would still make it public.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.