Year-End Discount: 10% OFF 1-year and 20% OFF 2-year subscriptions!

Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
js
file reading

What is the JavaScript file reader?

Educative Answers Team

Tired of LeetCode? 😩

Learn the 24 patterns to solve any coding interview question without getting lost in a maze of LeetCode-style practice problems. Practice your skills in a hands-on, setup-free coding environment. 💪

The file reader is a JavaScript object that is used to read files stored in a computer. It does this asynchronously, meaning that the application does not block while a file is being​ read.

svg viewer

The file reader can create various representations of the file being read, but the desired representation must be specified by calling the appropriate method. For instance,

  • the readAsText() method should be called when a file needs to be read as plain text.

  • the readAsDataUrl() method should be used to encode a file in a string that can be used as a URL.

Since the file reader can read files asynchronously, it has some events that can be listened for. These include:

  • load, it is fired when a read has finished successfully.
  • error, it is fired when an error occurs during a read.

Example

Reading a file as plain text

  1. A FileReader() object is created.
  2. The readAsText() method is called because the file needs to be read as plain text.
  3. A function is created that will be called when the onload event fires. In this case, the content of the file is being printed.
  4. A function is created that will be called when the error event fires. In this case, the error will be printed on the console.
  • HTML
Console

RELATED TAGS

javascript
js
file reading
Copyright ©2022 Educative, Inc. All rights reserved

Tired of LeetCode? 😩

Learn the 24 patterns to solve any coding interview question without getting lost in a maze of LeetCode-style practice problems. Practice your skills in a hands-on, setup-free coding environment. 💪

Keep Exploring
Related Courses