javascriptcsvpapaparse

How to parse CSV from file with PapaParse?


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.


Solution

  • 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.