How can you read a local text file in the browser using the JavaScript FileReader API? | A1Lab@FahadM to JavaScriptEnglish • 5 days ago

How can you read a local text file in the browser using the JavaScript FileReader API?

message-square
0

To read a local text file selected by the user in the browser using the FileReader API, create a new FileReader(), attach onload (for the resulting text in event.target.result) and onerror handlers, and call reader.readAsText(file, "utf-8") on the File object from an <input type="file"> change event or drag-and-drop drop event. Because FileReader is event-driven, wrapping it in a Promise makes it easy to consume with async/await.


1. Reading a Selected File with FileReader.readAsText()

Listen to a file input’s "change" event, grab event.target.files?.[0], and read its contents as UTF-8 text:

// Wrap FileReader.readAsText in a Promise for clean async/await usage
function readTextFileAsync(file, encoding = "utf-8") {
  return new Promise((resolve, reject) => {
    if (!(file instanceof Blob)) {
      reject(new TypeError("Expected a valid File or Blob object"));
      return;
    }

    const reader = new FileReader();

    reader.onload = (event) => {
      resolve(String(event.target?.result ?? ""));
    };

    reader.onerror = () => {
      reject(reader.error ?? new Error("Failed to read file"));
    };

    reader.readAsText(file, encoding);
  });
}

// Wire up to an <input type="file" id="text-file-input" accept=".txt,.csv,.json,.md" />
const fileInput = document.getElementById("text-file-input");
fileInput?.addEventListener("change", async (event) => {
  const selectedFile = event.target.files?.[0];
  if (!selectedFile) {
    return;
  }

  try {
    const fileContent = await readTextFileAsync(selectedFile, "utf-8");
    console.log("File name:", selectedFile.name, "Length:", fileContent.length);
    console.log("Content preview:", fileContent.slice(0, 200));
  } catch (err) {
    console.error("Error reading local file:", err);
  }
});
  • reader.readAsText(file, "utf-8"): Starts asynchronous reading and decodes bytes into a string using the specified character encoding ("utf-8" by default).
  • event.target.result inside onload: Holds the file text once reading finishes successfully.
  • reader.onerror and reader.error: Handle read failures or aborted reads cleanly instead of letting errors go unhandled.

2. Validating File Size and Type Before Reading

Before calling readAsText(), check file.size and file name/MIME type so users do not accidentally freeze the tab with huge files or pass unexpected formats:

// Validate file size and extension before reading with FileReader
function validateTextFile(file, { maxBytes = 2 * 1024 * 1024, allowedExtensions = [".txt", ".log", ".json", ".csv"] } = {}) {
  if (!file) {
    return { ok: false, reason: "No file selected" };
  }

  if (file.size > maxBytes) {
    return { ok: false, reason: `File exceeds ${maxBytes} bytes limit` };
  }

  const lowerName = file.name.toLowerCase();
  const hasAllowedExt = allowedExtensions.some((ext) => lowerName.endsWith(ext));
  if (!hasAllowedExt) {
    return { ok: false, reason: "Unsupported file extension" };
  }

  return { ok: true, reason: "" };
}

const sampleMeta = validateTextFile({ name: "notes.txt", size: 1024 });
console.log("Validation result:", sampleMeta);
  • Guard large files: Reading multi-hundred-megabyte files into a single string via readAsText() can spike memory or slow down the browser.
  • Reset input.value = "" if needed: Clearing fileInput.value = "" after processing allows re-selecting the exact same file name again to trigger "change".

3. Common Traps to Avoid

Using FileReader in the browser trips up developers on timing, encoding, and browser sandboxing:

  • Reading reader.result synchronously right after calling reader.readAsText(file): readAsText() is asynchronous—reader.result is null immediately after calling it and is only populated once "load" / onload fires (or via await on a Promise wrapper).
  • Assuming you can pass an arbitrary local path string like "C:\\docs\\a.txt": Browser security sandboxes prevent scripts from reading arbitrary filesystem paths directly; files must come from user selection (<input type="file">, drag-and-drop, or file picker APIs).
  • Reusing the same FileReader instance across concurrent reads: Create a fresh new FileReader() per file read so overlapping events and reader.result values do not collide.

TL;DR: Create new FileReader(), attach onload and onerror, and call reader.readAsText(file, "utf-8") on a user-selected File object (ideally wrapped in a Promise for async/await).

Are you reading files from an <input type="file">, handling drag-and-drop uploads, or parsing CSV/JSON text after loading?