Categories
JavaScript Answers

How to Read a Local Text File with JavaScript?

Spread the love

Sometimes, we may want to read a text file stored on a user’s computer with JavaScript.

In this article, we’ll look at how to read a local text file stored on the user’s device with JavaScript.

Get File Content from File Input

We can read file content from a file selected with the file input into our web page.

For instance, we can write the following HTML:

<input type='file' accept='text/plain'>

to add the file input.

Setting accept to text/plain makes the file input only accept plain text files.

And we can add a change event listener to the file input by writing:

const fileInput = document.querySelector('input')
fileInput.addEventListener('change', (event) => {
  const input = event.target;
  const reader = new FileReader();
  reader.onload = () => {
    console.log(reader.result);
  };
  reader.readAsText(input.files[0]);
})

We call addEventListener to 'change' to add a change listener.

Then we get the input with event.target .

And we create a FileReader instance to let us read a file.

We set the onload listener to get the text read from a file with the reader.result property.

Then to read the file, we call reader.readAsText with the first selected file, which is stored in input.files[0] .

Also, we can substitute readAsText with readAsBinaryString to get the same result:

const fileInput = document.querySelector('input')
fileInput.addEventListener('change', (event) => {
  const input = event.target;
  const reader = new FileReader();
  reader.onload = () => {
    console.log(reader.result);
  };
  reader.readAsBinaryString(input.files[0]);
})

Read Text of a Selected File with the text Method

The object with the selected file has the text method to let us read the text from the file object directly.

It returns a promise with the text.

For instance, we can write:

const fileInput = document.querySelector('input')
fileInput.addEventListener('change', async (event) => {
  const text = await event.target.files[0].text()
  console.log(text)
})

to call the text method on the event.target.files[0] file object.

The text variable would then have the text we read from the selected file.

We keep using the file input HTML that we written before.

Conclusion

We can read a file from the FileReader instance or the text method of the selected file object.

By John Au-Yeung

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

One reply on “How to Read a Local Text File with JavaScript?”

Leave a Reply

Your email address will not be published. Required fields are marked *