0

Is it possible to open a file with Javascript?

Its all local so I have a index.html in which the javascript should read a text file which is in the same direction called readText.txt

I heard that there are some security restrictions but if its all local shouldn't it work? If no is there any workaround? I've googled some and found the Mozilla FileHandleApi but It doesn't work for me

kovogel
  • 1,030
  • 3
  • 11
  • 19

2 Answers2

2

JS is executed on client, client has no notion of server files. But you can use AJAX to request a file if you have URL. You can do something like $.get('readText.txt') (jQuery) from index.html.

FileHandleApi is used to manipulate client files.

It is important to understand what is server here and what is client and where what is executed. Server is a machine that serves pages (and files). Client is the machine where the browser runs. Server and client communicate via network. You can run server on your local machine but this doesn't change the nature of the relationship.

Andrey
  • 59,039
  • 12
  • 119
  • 163
  • I'm not sure the OP realizes that a file in the same directory as index.html on his local box is a 'server file' as far as the browser is concerned. – Jared Smith Jul 14 '15 at 12:29
  • @JaredSmith probably. Well if you don't where is server where is client it is hard to develop web apps. – Andrey Jul 14 '15 at 12:31
  • We all started somewhere, and the relationship is not necessarily intuitive to a beginner. – Jared Smith Jul 14 '15 at 12:38
0

The short answer is no, what you're attempting will not work.

The longer answer: That's not how the web works, even on your local machine. Its a strictly client/server relationship: your browser doesn't (and shouldn't) care that the client and the server in this case are the same machine. As far as your browser knows, that readme.txt file is on the 'server' and needs to be fetched with an AJAX call. The browser (for the security reasons you mentioned) can only (for our purposes here) manipulate client files it creates. The filehandle API is for that purpose.

Jared Smith
  • 19,721
  • 5
  • 45
  • 83