Course contentsShow
← Web Development
Lesson 2695 of 2,98248. File Uploads and HandlingFree lesson

Aborting File Reads

Using the abort() method to cancel in-progress file read operations.

Aborting File Reads

You'll learn how to cancel a file read operation that's already in progress using the FileReader's abort() method.

Why Cancel a File Read?

When reading large files or when user actions change mid-operation (like selecting a different file or clicking "Cancel"), you need a way to stop the current read. Leaving an unwanted read operation running wastes resources and can cause unexpected behavior when it completes.

Think of it like streaming a video: if you decide you don't want to watch it anymore, you hit "stop" rather than letting it buffer the entire file in the background.

The abort() Method

Every FileReader instance has an abort() method that immediately stops the current read operation. When called, it:

  1. Halts the read process
  2. Triggers the abort event on the FileReader
  3. Sets the FileReader's error property to a DOMException with name "AbortError"
const reader = new FileReader();
const file = fileInput.files[0];

reader.onabort = () => {
  console.log('Read operation was cancelled');
};

reader.onerror = () => {
  if (reader.error.name === 'AbortError') {
    console.log('Read was aborted');
  }
};

reader.onload = () => {
  console.log('This won\'t run if aborted');
};

reader.readAsText(file);

// User changes their mind
cancelButton.onclick = () => {
  reader.abort(); // Immediately stops the read
};

The abort event fires instead of the load or error events (unless the error is the abort itself). The loadend event still fires, giving you a final hook for cleanup.

Key Takeaway: Use abort() on a FileReader instance to immediately cancel an in-progress file read, triggering the abort event and preventing the load handler from executing.