首页 > 解决方案 > 如何使用 js 从 Github 存储库中创建包含文件的数组?

问题描述

我正在使用 HTML 创建一个网站,并且我想创建一个包含我放入 Github 存储库中的 midi 文件的表。为此,我只是想象自己将所有这些文件插入到一个数组中,然后根据数组中的文件生成表。将文件的名称存储在一个数组中,然后根据名称查找文件可能也可以。

但问题是我不知道如何获取位于文件夹(位于 Github 存储库中)中的所有文件(或其名称)。这感觉像是一件非常简单的事情,但我已经搜索了一段时间,并没有发现任何帮助。

那么,有人知道我如何使用 js 从 Github 存储库中创建一个包含文件的数组吗?

标签: javascripthtmlarraysfilegithub

解决方案


在查看了 GitHubs API 之后,我发现了一个可以让我获取存储库内容的东西!

    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();

API 调用返回一个包含存储库内容的 JSON 字符串,这非常适合我的情况。

这是 API 文档的链接:https ://docs.github.com/en/rest/reference/repos#get-repository-content

这是一个帮助我理解 GitHub API 的网站:https ://codesnippet.io/github-api-tutorial/

我要感谢@user2190492建议使用 GitHub API。


推荐阅读