Reading a local CSV file in JavaScript can be done using the FileReader
API and the Papa Parse
library. Here’s an example of how you can use the FileReader
API to read a local CSV file:
const input = document.getElementById("csv-file");
input.addEventListener("change", function(event) {
const file = event.target.files[0];
const reader = new FileReader();
reader.readAsText(file);
reader.onload = function() {
const csvData = reader.result;
console.log(csvData);
};
});
In this example, a file input is created using HTML and a change event listener is added to it using JavaScript. When a file is selected, the FileReader
API is used to read the file as text and the result
property of the reader is used to access the content of the file. The content of the file is logged to the console.
Alternatively, you can use the Papa Parse
library to parse the CSV data into a structured format, such as an array of objects. Here’s an example of how you can use Papa Parse
to read a local CSV file:
const input = document.getElementById("csv-file");
input.addEventListener("change", function(event) {
const file = event.target.files[0];
Papa.parse(file, {
header: true,
complete: function(results) {
console.log(results.data);
}
});
});
In this example, the Papa.parse
function is used to parse the file into a structured format. The header
option is set to true
so that the first row of the CSV file is treated as the header row and used to create property names for each object. The complete
option is used to specify a callback function that is executed when the parsing is complete. The results.data
property is used to access the parsed data, which is logged to the console.
+ There are no comments
Add yours