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

Reading Files as Text

Using readAsText() to read file contents as plain text with optional encoding parameters.

Reading Files as Text

You'll learn how to use readAsText() to convert file contents into a plain text string for display or processing.

Now that you've created a FileReader instance, the next step is putting it to work. The readAsText() method instructs your FileReader to read a file and interpret its contents as plain text—perfect for reading .txt files, .json configs, code files, or any text-based format.

How It Works

Think of readAsText() like asking someone to read a book aloud: you hand them the file, and they convert the bytes into readable words. The method starts an asynchronous read operation, and when finished, the text appears in the FileReader's result property.

Basic usage looks like this:

const reader = new FileReader();

reader.addEventListener('load', (event) => {
  const textContent = event.target.result;
  console.log(textContent); // The file's text content
});

reader.readAsText(file); // file from input or drop event

Encoding Parameter

The method accepts an optional second parameter for character encoding: reader.readAsText(file, 'UTF-8'). While UTF-8 is the default (and handles most cases), you might need 'ISO-8859-1' for older files or 'UTF-16' for specific use cases.

// Reading a file with specific encoding
reader.readAsText(file, 'ISO-8859-1');

This is particularly useful when handling files from legacy systems or internationalized content that uses non-standard encodings.

Key Takeaway: readAsText() converts file bytes into readable strings asynchronously, with UTF-8 as the default encoding and the option to specify alternatives for special cases.