Sometimes, we want to read in a local csv file in JavaScript.
In this article, we’ll look at how to read a csv file in JavaScript.
How read a csv file in JavaScript?
To read a csv file in JavaScript, we can use the FileReader constructor.
For instance, we write:
<input type="file">
to add a file input.
Then we write:
const input = document.querySelector('input')
const fileReader = new FileReader()
fileReader.onload = (e) => {
console.log(e.target.result)
}
input.onchange = (e) => {
const [file] = e.target.files
fileReader.readAsBinaryString(file)
}
to select the input with querySelector.
Next, we create a FileReader instance.
Then we set its onload property to a function that logs the file content.
Next, we set input.onchange to a function that gets the selected file from e.target.files.
And then we call fileReader.readAsBinaryString to read the file.
Conclusion
To read in local csv file in JavaScript, we can use the FileReader constructor.