JavaScript File Encoding
Quick answer
FileReader reads Blob or File data and reports results through events. For simple promise-based reads, Blob.text and Blob.arrayBuffer are often easier.
How it works
Create a reader, attach load and error handlers, then call readAsText(blob) or readAsArrayBuffer(blob). The call starts the operation and returns undefined; result is available after completion. abort() requests cancellation while reading. loadend also fires after failures or cancellation, so it does not by itself indicate success. Avoid reading very large files into memory without bounds.
Local examples
Run in a fresh browser document. Uses synthetic local data; actual ByteMind editor support is unverified.
(async () => {const r=new FileReader();const out=await new Promise((resolve,reject)=>{r.onload=()=>resolve(r.result);r.onerror=()=>reject(r.error);r.readAsText(new Blob(["abc"]));});console.log(out,r.readyState);})()Expected console output:
abc 2Ready state 2 means DONE.
Run in a fresh browser document. Uses synthetic local data; actual ByteMind editor support is unverified.
(async () => {const r=new FileReader();const b=await new Promise((resolve,reject)=>{r.onload=()=>resolve(r.result);r.onerror=()=>reject(r.error);r.readAsArrayBuffer(new Blob([new Uint8Array([7,8])]));});console.log(JSON.stringify([...new Uint8Array(b)]));})()Expected console output:
[7,8]The result contains the original two bytes.
Common mistakes
Do not read reader.result immediately after starting. Handle load, error and abort separately in real UI code.
Practice
Read a constructed Blob, handle success and failure, and explain how a cancel button would abort an active read.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
FileReader: asynchronous reading and events — Knowledge Check
Apply the concept and reason about local example output.
When is FileReader.result ready for a successful read?
Which event can occur after a failed read as well as a successful one?
What can simplify a text read when progress events are unnecessary?
What is the expected console output of FileReader: asynchronous reading and events example 1?
(async () => {const r=new FileReader();const out=await new Promise((resolve,reject)=>{r.onload=()=>resolve(r.result);r.onerror=()=>reject(r.error);r.readAsText(new Blob(["abc"]));});console.log(out,r.readyState);})()What is the expected console output of FileReader: asynchronous reading and events example 2?
(async () => {const r=new FileReader();const b=await new Promise((resolve,reject)=>{r.onload=()=>resolve(r.result);r.onerror=()=>reject(r.error);r.readAsArrayBuffer(new Blob([new Uint8Array([7,8])]));});console.log(JSON.stringify([...new Uint8Array(b)]));})()