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.
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
- A
FileReader()object is created. - The
readAsText()method is called because the file needs to be read as plain text. - A function is created that will be called when the
onloadevent fires. In this case, the content of the file is being printed. - A function is created that will be called when the
errorevent fires. In this case, the error will be printed on the console.
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved