Reputation: 3637
I can't find a single bit of information about how to do this, so I'm resorting to asking a question here.
How do I actually load a local file and parse it using PapaParse?
I currently have:
$(function() {
Papa.parse(new File("text.csv"), {
complete: function(results)
console.log("Finished:", results.data);
}
});
});
...but I have decided the constructor must be intended for creating new files. How am I supposed to do this? PapaParse's website shows this:
Papa.parse(file, {
complete: function(results) {
console.log("Finished:", results.data);
}
});
...buuut that doesn't explain where file
came from.
Upvotes: 3
Views: 3329
Reputation: 11
the best is to use Fetch() Api like this :
<script>
window.onload = function(e) {loadCsv()} ;
function loadCsv() {
let file = "data/medic.csv"
fetch (file)
.then(x => x.text())
.then(y => {
var data = Papa.parse(y, {header: true}).data;
// console.log(data[0].num) ;
document.getElementById("test").innerHTML = data[0].num;//num : fieldname
});
}
</script>
Upvotes: 0
Reputation: 897
You need to read the file from the system before trying to parse it.
If you are trying this in a web application, you could add a file uploader and call Papa.parse() after an event: i.e. either when file changes, or at the click of a button.
<input type="file" id="fileInput" />
Then you need to add an onchange
or onclick
event function accordingly.
Inside the event function, you can access the file as:
event.target.files[0]
If you are using this on a server, you can use any filesystem methods to read your file.
Like in Node.js we have fs.readFile()
function to read a file from the system at a given path.
Upvotes: 4