Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Preserve formatting while fetching GitHub file contents

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading