One can fetch the contents of a file in a GitHub repository using the code below.
fetch("https://raw.githubusercontent.com/Ayanmullick/test/master/AutomationAcc/test1.ps1")
.then(response => response.text())
.then(data => document.write(data))
However, the formatting gets lost. I faced the same problem with the api too.
fetch("https://api.github.com/repos/Ayanmullick/test/git/blobs/97e69f38b60f360dc8a22e07c6c395feb0e004a8")
.then(response => response.json())
.then(data => atob(data.content))
.then(decoded =>document.write(decoded))
Is there a way to preserve the formatting while fetching the file contents?
CodePudding user response:
The issue isn't that fetch()
is loosing your formatting, it is that document.write()
won't write whitespace. You can see this by console.log()
ing instead:
fetch("https://raw.githubusercontent.com/Ayanmullick/test/master/AutomationAcc/test1.ps1")
.then(response => response.text())
.then(data => console.log(data))
If you need to write it to the DOM, try using a <pre>
tag that preserves whitespace exactly:
fetch("https://raw.githubusercontent.com/Ayanmullick/test/master/AutomationAcc/test1.ps1")
.then(response => response.text())
.then(data => document.getElementById('code').textContent = data)
<pre id="code"></pre>