What is the JavaScript file reader?

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

Copyright ©2024 Educative, Inc. All rights reserved