简体   繁体   中英

How to read text file from filesystem in JavaScript

I have tried different approaches to read a text file from the local file system in JavaScript and display the content of the file in alert() but all to no avail.

Approach 1

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.response;
                     document.getElementById("content").innerText = allText;
                      alert(allText);
                  }
              } else {
                  alert("Can't read the file");
              }
          }
          rawFile.send(null);
    }
    readTextFile("FormulaQuestion.txt");

The FormulaQuestion.txt file is in the same directory with the html file, this approach shows an empty alert window on the browser

Approach 2 using fetch method

fetch('FormulaQuestion.txt')
        .then(response => response.text())
        .then((data) => {
            alert(data);
        })

This doesn't show anything

Approach 3 using JQuery

$.get('FormulaQuestion.txt', function (data) {
        alert(data)
    }, 'text');

This doesn't work either.

I am building a desktop application that uses a web browser control to load html file which is embedded into the application. The application reads the string from sqlite database and save it in the FormulaQuestion.txt file, then refreshes the WebControl component which reloads the html file. Now when the html file is reloaded, the JavaScript should read the text file and display it on alert() which once the alert is able to display the file content, i will then set it to a paragraph and remove the alert() . Please someone should help me out.

Browsers by design do not allow access to the file system for JavaScript, as allowing such access would be a serious security concern.

To provide the FormulaQuestion.txt file to your script you will need to host the file on a server and request it via a HTTP request (like with your fetch). The key thing here is that a server is needed to actually transmit the file over the HTTP protocol to your script.

If working locally, there are many options for running a local server.

  • The npm serve module,
  • Wamp
  • Apache

You may also want to try out some free tier services like Vercel or Netlify. Both I believe allow you to just drag/drop a file and it will host it for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM