-3

Is there any way to get the content of a text file (txt/jss/html/...) with javascript or any other way, inserting it to a variable? (Also jquery is ok) I mean: abc.txt contains some text, that ttext should be stored into a variable. Thanks

Xarber
  • 25
  • 7

1 Answers1

0

Yeah, it's pretty straightforward all you have to do is change the string a little bit like so, for example here is json file from a github repo

https://github.com/arnav7633/tej.js/blob/main/tsconfig.json

now that string gets changed to

https://raw.githubusercontent.com/arnav7633/tej.js/main/tsconfig.json

The domain changes. Then make a simple axios/fetch query to that URL enter image description here

(async() => {
const res = await axios.get("https://raw.githubusercontent.com/arnav7633/tej.js/main/tsconfig.json")
console.log(res.data)
})()
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Arnav Mishra
  • 488
  • 2
  • 15
  • Thats kinda what i was searching for, but is there a way to do it from javascript? curl is not a js function. – Xarber Mar 16 '22 at 14:48
  • I was just demonstrating that changing the domain works, it would result in the same response from any library be it curl or axios @Xarber – Arnav Mishra Mar 16 '22 at 16:14
  • I mean, changing the domain is ok, but i want to get the content of the page inside a variable, so it can be used later. What i got into is the fetch function, but most times it returns undefined or null. Is there any other way? – Xarber Mar 16 '22 at 19:26
  • As you can see from the snippet it loads fine, can you show me the link you tried? @Xarber – Arnav Mishra Mar 17 '22 at 03:08
  • Nevermind, now it works. I found a js bug: If you save the fetch results in localStorage when you get it sometimes it could bug and give you the same result twice. I mean: put fetch in a function; I Call fetch fetch returns 'hi' > Save 'hi' in localStorage Insert LocalStorage to a var var = 'hi'; I Call fetch on a different link fetch returns 'hi2' > Save 'hi2' in localStorage Insert LocalStorage to a var var = 'hi'; That was my problem so i just put all of the code inside the fetch 'then' function and now it works. Still thanks for the raw github link. – Xarber Mar 17 '22 at 14:02
  • Oh cool didn'know this worked too, thanks – Xarber Mar 18 '22 at 06:05