Home > Software design >  How to create an array with files from a Github repository with js?
How to create an array with files from a Github repository with js?

Time:10-14

I'm making a website with HTML, and I want to create a table with midi files that I've put in a Github repository. For this I just imagined myself inserting all of these files into an array, and then generating the table based on the files in the array. Storing the names of the files in an array and then just finding the file based on the names would probably also work.

But the issue is that I have no idea how to get all files (or their names) located in a folder (which is in a Github repository). This feels like a pretty simple thing to do, but I've searched for a while and found nothing that helped.

So, does anybody know how I could create an array with files from a Github repository with js?

CodePudding user response:

After looking through GitHubs API I found a thing that lets me get the contents of a repository!

    const xhr = new XMLHttpRequest();
    const url = "https://api.github.com/repos/-username-/-repo-/contents/:path"
    // Replace -username- with your GitHub username, -repo- with the repository name, and then :path with a path to the file or folder you want to get the content of (leave blank to ge all files of the repository)

    xhr.open('GET', URL, true);

    xhr.onload = function() {
        const data = JSON.parse(this.response);

        console.log(data);
    };
    
    xhr.send();

The API call returns a JSON string with the content of the repository, which is perfect for my case.

Here is a link to the API documentation: https://docs.github.com/en/rest/reference/repos#get-repository-content

Here is a website which helped me understand GitHub API: https://codesnippet.io/github-api-tutorial/

And I want to thank @user2190492 for suggesting to use the GitHub API.

  • Related