Home >Web Front-end >JS Tutorial >How Can I Efficiently Read Local Text Files in a Web Browser?

How Can I Efficiently Read Local Text Files in a Web Browser?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-19 04:11:11829browse

How Can I Efficiently Read Local Text Files in a Web Browser?

Reading Local Text Files in the Browser

XMLHttpRequest is a commonly used method for asynchronous data retrieval in the browser, but it can sometimes encounter issues when attempting to read local text files.

Issues with XMLHttpRequest

One common error is XMLHttpRequest exception 101, which indicates that the request has been aborted. This can occur when attempting to read local files without specifying the "file://" protocol.

Alternative: Fetch API

A more straightforward way to read local text files is through the Fetch API, introduced in 2015. Example code using the Fetch API to read a local file named "myText.txt":

fetch("myText.txt")
  .then((res) => res.text())
  .then((text) => {
    // Process the text data
  })
  .catch((e) => console.error(e));

Accessing Local Files

Modern browsers impose strict restrictions on direct filesystem access. Avoid using "file:///". Instead, consider using lightweight webservers like Python -m http.server or npx http-server to load data via regular HTTP URLs.

Example Code with XMLHttpRequest

If using XMLHttpRequest, manually check for status 0 (indicating local files) instead of relying on a returned status code:

function readTextFile(file) {
  var rawFile = new XMLHttpRequest();
  rawFile.open("GET", file, false);
  rawFile.onreadystatechange = function () {
    if (rawFile.readyState === 4) {
      if (rawFile.status === 200 || rawFile.status === 0) {
        var allText = rawFile.responseText;
        console.log(allText);
      }
    }
  };
  rawFile.send(null);
}

Specifying File Path

Remember to include the "file://" protocol when specifying the file path:

readTextFile("file:///C:/your/path/to/file.txt");

The above is the detailed content of How Can I Efficiently Read Local Text Files in a Web Browser?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn