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.
Asked
Active
Viewed 994 times
0
-
Please provide enough code so others can better understand or reproduce the problem. – Community Apr 04 '22 at 17:54
1 Answers
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);
}
});

Quentin
- 914,110
- 126
- 1,211
- 1,335
-
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? – Sarah Apr 04 '22 at 08:56
-
"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. – Quentin Apr 04 '22 at 08:57
-
"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. – Quentin Apr 04 '22 at 08:58
-
"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**. – Quentin Apr 04 '22 at 08:59
-
"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**. – Quentin Apr 04 '22 at 08:59
-
Because the JSON loader parses the JSON into a JavaScript data structure and a loader which gives you a string doesn't. They just have different end goals. – Quentin Apr 04 '22 at 09:01