Categories
JavaScript Answers

How to read a local csv file in JavaScript?

Spread the love

To read in a local 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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.