Roberto
Roberto

Reputation: 21

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.

Upvotes: 1

Views: 1908

Answers (2)

Dart Von Grell
Dart Von Grell

Reputation: 11

If you are using Chrome, you need to run Chrome with the "--disable-web-security" command line parameter, but I don't know about Firefox/other browsers.

Upvotes: 1

William Forty
William Forty

Reputation: 252

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.

Upvotes: 2

Related Questions