1

Lets consider that I have a text file named text.txt. So, now I made a file named showtext.html in which I have to write javascript such that it can display the text present in text.txt. I assume it would be like :

Text ( text.txt )

 Show me up !

HTML ( showtext.html )

<!DOCTYPE html>
<html>
<body>
<script>
   var src = "text.txt";
   document.write( value.get( src ) );
</body>
</html>

Output of showtext.html

Show me up !

In, the above function the value.get() gets and then writes the value of the text.txt. So, can javascript really do such ? How can I make the value.get() ? Will it support only .txt extension or can support any custom extension ? Or this can only be done with PHP ?

7
  • 1
    Are you trying to read the file from the client or the server? Commented Oct 31, 2019 at 15:33
  • Yes, this is possible to do in JS and much of the web relies on this capability. The 2 simple approaches are either 1) Serve your text.txt at a URL and make an https request to fetch it from the client, and 2) have a build step that replaces placeholders with the contents of text.txt. Commented Oct 31, 2019 at 15:34
  • No, I am not using any server or client, it is present locally !! Commented Oct 31, 2019 at 15:34
  • @junvar please add a working example Commented Oct 31, 2019 at 15:35
  • Reading files, not so much. JavaScript doesn't have any sense about the server's file system. However, retrieving data is of course possible, e.g. see this question. So if there is a server component that can handle the request, then you're all set. Commented Oct 31, 2019 at 15:35

1 Answer 1

0

"Local" means "all client, no server" :) If you don't have a server, you can't use things like fetch() (as far as I know, security restrictions prevent that). But you can read a file from the local computer on the client as long as the user selects the file themselves. You can't just read any arbitrary file from the client's computer (again, for security reasons).

If you're okay with letting the user select the file, look into the FileReader API.

HTML:

<input type='file' id='fileSelector' />

JS:

const fileInput = document.getElementById('fileSelector');
fileInput.addEventListener('change', event => {
  const file = event.target.files[0];
  const reader = new FileReader();
  reader.addEventListener('load', readEvent => {
    // In here, readEvent.target.result will have the text of the file for you to work with.
  });
  reader.readAsText(file);
});
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.