Process csv files at browser
A couple of week's ago I had to write a task that uploads, parses and processes a CSV file, all at client side (browser).
And it was surprisingly simple.
Given a file input:
<input type="file" />
Handle the files is a matter of adding a change listener:
const inputElement = document.querySelector("input[type=file]");
inputElement.addEventListener("change", () => {
const file = inputElement.files[0]; // assuming there's only one file
console.log("file type: ", file.type)
console.log("size in bytes:", file.size)
}
FileReader API can be used to read the contents of the file:
inputElement.addEventListener("change", () => {
const file = inputElement.files[0]; // assuming there's only one file
const reader = new FileReader();
reader.onload = (event) => {
console.log("text contents", event.target.result)
};
fileReader.readAsText(file, "UTF-8");
}
Of course, FileReader can read files in binary formats too.
To process the actual CSV contents I used the fantastic PapaParse library, that has file input support out of the box (so I didn't have to use FileReader API directly):
const Papa = require("papaparse");
input.on("change", (event) => {
const file = event.target.files[0];
Papa.parse(file, {
header: true,
complete: (results) => console.log(results)
// ☝️results is an array of one object per row
})
})
Processing files in client side can have several advantages (for example, validating the size without need to upload).
I think we should do it more!
🖖