-2

Why won't this read my file!? What am I missing

NOTE - I also get warning : XMLHttpRequest on the main thread is deprecated because - not sure what else to use?

<script>
function readTextFile(file)
       {
           var rawFile = new XMLHttpRequest();
           rawFile.open("GET", file, true);
           rawFile.onload= function (){
               if(rawFile.readyState === 4)
               {
                   if(rawFile.status === 200 || rawFile.status == 0)
                   {
                       var allText = rawFile.responseText;alert(allText);
                       console.log(alltext);
                   }    
                }
           }
        }
        var test = readTextFile("file:///C:/Users/.../Desktop/***.txt")
        console.log("test"+ test); //undefined
</script>
Nathaniel Flick
  • 2,902
  • 2
  • 22
  • 31
  • *XMLHttpRequest on the main thread is deprecated* read the FULL message ... you're using *synchronous* XHR which is deprecated ... in fact, you use synchronous XHR AND `onreadystatechange` - which is an odd combination, use *asynchronous* XHR and use `onload` instead of `onreadystatechange` ... – Jaromanda X Dec 10 '19 at 01:42
  • `new AsyncXMLHttpRequest` ? – TexteryReason Dec 10 '19 at 01:45
  • no, there's no such thing ... just don't make XMLHttpRequest asynchronous in `.open` – Jaromanda X Dec 10 '19 at 01:52
  • `rawFile.open("GET", file, true);` – Jaromanda X Dec 10 '19 at 03:46
  • Didn't work. :( – TexteryReason Dec 10 '19 at 13:30
  • didn't work ... so, errors in the console? are you opening that file using a page opened using `file:///` protocol? – Jaromanda X Dec 10 '19 at 13:32
  • No errors. I print `var test`in the console but it's undefined. I think `rawfile` itself is undefined and I don't understand why. Furthermore coming from an OOP background I'm confused why reading a txt file into a object is so difficult. even after changing the `true` parameter in `rawfile.open` – TexteryReason Dec 10 '19 at 22:25
  • You can’t read local files by path from browser JavaScript, even when the JavaScript is itself inside a local file. That would be a big security hole. There should be an error about that in your console. – Ry- Dec 10 '19 at 23:12
  • (You may have copied this from an example that used to work in 2010 in some browsers, but I’m pretty sure it doesn’t now. If it does, that’s extremely bad.) – Ry- Dec 10 '19 at 23:13
  • In any programming language you can take a local text file and read it into a object or variable in this case, js should not be any different, so what gives? This is very possible, it has to be. – TexteryReason Dec 10 '19 at 23:15
  • Yes I have, because it was the top solution for doing this, so my question is.. what is the right way to do this if this is not? I can't find any good simple documentation on how to accomplish such an easy task. – TexteryReason Dec 10 '19 at 23:16
  • In any programming language *targeted at a browser environment*, no, you cannot. Browsers let you open webpages with an expectation that they won’t be able to read random files from your computer. If you run JavaScript in an environment that matches other languages you’ve used, like Node.js, then you can do things normal local processes can do. So: what are you trying to accomplish by reading a file? – Ry- Dec 10 '19 at 23:17
  • I simply want to read the contents of a text file into a javascript variable, at which I can manipulate in different ways via javascript Can you point me in the direction of some documentation that can help me accomplish such a task as this? – TexteryReason Dec 10 '19 at 23:18
  • Not without knowing what “such a task as this” is. You can want to read a file for many reasons. The answer depends on which. – Ry- Dec 10 '19 at 23:18
  • Sorry I just saw you asking, see above your comment. My Badddd – TexteryReason Dec 10 '19 at 23:19
  • Open the text file in Notepad, Ctrl+A, Ctrl+C. Open your HTML file in Notepad, ``var allText = `(Ctrl+V)`;``. You now have the contents of a text file in a JavaScript variable. – Ry- Dec 10 '19 at 23:21
  • No this would be dynamic, I would be reading in a file on a server somewhere not just locally. Hence the path – TexteryReason Dec 10 '19 at 23:22
  • So you want to read a text file from the same server that’s going to be serving your webpage? – Ry- Dec 10 '19 at 23:23
  • No I would be reading in a file from some server into a javascript variable, and do what I so please with the data. – TexteryReason Dec 10 '19 at 23:24
  • So the server with the file you want to read is *not* the same server that’s going to be serving the webpage with your JavaScript? – Ry- Dec 10 '19 at 23:25
  • More than likely not, because the goal here, is as follows, a server hosing lets say x number of dictionaries, but in this case I'm testing with A dictionary, and I want to compare that dictionary to certain things on A website. – TexteryReason Dec 10 '19 at 23:27
  • but for testing purposes, they were, because in every other language thats an easy ask to read in a file – TexteryReason Dec 10 '19 at 23:27
  • If you don’t control that other server and that server doesn’t explicitly opt in to letting you make requests to it through either CORS or some older technology like JSONP, this is also not possible from JavaScript on a webpage, again for security reasons. – Ry- Dec 10 '19 at 23:28
  • Do you *need* to implement this as a webpage, or can it just be a regular program? – Ry- Dec 10 '19 at 23:29
  • Okay, well this is getting to complicated, so let me ask you what I should do, I don't know js, SO if you wanted to have txt files you needed to read into a js script to compare them to data off a webpage, what is the best way to do this? – TexteryReason Dec 10 '19 at 23:30
  • It will be running as a plugin, so I thought this would be the best route? – TexteryReason Dec 10 '19 at 23:30
  • A plugin as in a browser extension? – Ry- Dec 10 '19 at 23:32
  • correct. Unless there is a difference – TexteryReason Dec 10 '19 at 23:35
  • Okay, browser extensions are a completely different ballpark and you probably shouldn’t even bother starting with a local .html file, if that’s what this is. Make sure to mention that you’re building an extension in questions. Browser extensions still can’t read local files by path without the user specifically selecting them (e.g. with a file picker dialog or drag and drop), so you’ll need to test against some kind of server (maybe a local one¹). Then the question becomes “how do I make an HTTP request from a browser extension”, which is much more answerable. – Ry- Dec 10 '19 at 23:41
  • ¹ https://superuser.com/questions/231080/extremely-simple-web-server-for-windows has some. I recommend Python 3’s, `python3 -m http.server`. – Ry- Dec 10 '19 at 23:41

1 Answers1

1

For security reasons, the web browser is not allowed to read local files. You could however try running the app via the the same file:// protocol. Eg. type this URL in the browser address bar: file:///C:/Users/.../Desktop/myapp.htm (where myapp.htm is the app making the request)

The third argument in rawFile.open determines if the request should be async or not. In your example, the value is set to true (async) so I'm not sure why you get the deprecation warning. In newer browsers you can however use the Fetch API.

In order to read local files you could run a server on the user machine, that for example communicates with the web app using the HTTP protocol - and send the XMLHttpRequest (or fetch) to that server. If you decide to use a local server, make sure it requires authorization and use Content Security Policy properly.

user5886944
  • 174
  • 1
  • 7