使用 Node.js 从私有存储库下载 zip 版本

Sol*_*ber 4 github download node.js github-release private-repository

我正在尝试从私人存储库下载 zip 版本,我尝试了很多解决方案,但似乎都不起作用。

这是我的代码:

function Download(url, path, options) {
updateHeader(options.stageTitles.Downloading)
let received_bytes = 0;
let total_bytes = 0;

// eslint-disable-next-line
console.log('-----------------')
// eslint-disable-next-line
console.log(url, path)
console.log('-----------------')

var req = request(
    {
        method: 'GET',
        uri: url,
        headers: {
            Authorization: `token ${options.gitRepoToken}`,
            'Accept': 'application/octet-stream',
            'User-Agent': 'request module',
        },
        //encoding: null
    }
);

// eslint-disable-next-line
console.log(req)

var out = fs.createWriteStream(path);
req.pipe(out);

req.on('response', data => {
    // eslint-disable-next-line
    console.log(data.headers, data)
    total_bytes = parseInt(data.headers['content-length']);
});

req.on('data', chunk => {
    received_bytes += chunk.length;
    showProgress(received_bytes, total_bytes);
});

req.on('end', () => {
    Install(options)
});}
Run Code Online (Sandbox Code Playgroud)

url 变量等于:https: //github.com/SolberLight/PRIVATE_REPO_NAME/releases/download/1.0/MY_ZIP_NAME.zip

看起来我总是得到 9 字节的内容大小并带有“未找到”响应,所以我猜测我的标头不正确?

感谢您的帮助 !

编辑 1:取得了一些进展,但现在看来斑点的大小不正确

 (async () => {
    //get latest release
    var response = await axios.get(
        `https://api.github.com/repos/${repoWithOwner}/releases/latest`,
        {
            headers: authHeaders,
        }
    );
    var assets = response.data.assets;
    for (var i = 0; i < assets.length; i++) {
        console.log(assets[i].url);
        response = await axios({
            method: "get",
            url: assets[i].url,
            responseType: "blob",
            headers: {
                //Accept: "application/octet-stream",
                ...authHeaders,
            },
        });
        // eslint-disable-next-line
        console.log(response.data, path)

        let reader = new FileReader()
        reader.onload = function() {
            if (reader.readyState == 2) {
                var buffer = new Buffer(reader.result)
                console.log(`Saving ${JSON.stringify({ fileName: 'myfile.zip', size: response.data.size })}`)
                outputFile(path, buffer, err => {
                    if (err) {
                        // eslint-disable-next-line
                        console.log(err.message)
                    } else {
                        // eslint-disable-next-line
                        console.log(path)
                    }
                })
            }
        }
        reader.readAsArrayBuffer(response.data)
    }
})();
Run Code Online (Sandbox Code Playgroud)

Rub*_*epo 5

您可以使用此处记录的下载存储库存档 (zip) 端点

\n

考虑以下因素:

\n
    \n
  • 您将对 /repos/{owner}/{repo}/zipball/{ref} 执行 GET 请求

    \n
  • \n
  • 第一个请求将发送重定向(302响应),您需要正确遵循重定向,在这种情况下,由于您使用的是axios,因此您需要手动处理它。响应将包含您将在以下请求中使用的zipball_url 。

    \n
  • \n
  • 由于您正在下载私人存储库版本,因此请考虑这些链接是临时的,并会在五分钟后过期。

    \n
  • \n
  • 第一个请求接受用户或安装令牌(如果您将 API 作为 GitHub 应用程序使用)。在此处详细了解 GitHub 应用程序和 GitHub OAuth 应用程序之间的区别

    \n
  • \n
  • 如果您使用的是 GitHub OAuth 应用程序,请确保您具有存储库范围,对于 GitHub 应用程序,请确保您具有内容权限

    \n
  • \n
\n

查看以下工作示例:

\n
\n\n\n\n\n\n\n\n
从 GitHub 下载 zip 版本 \xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0 \xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2 \xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0 \xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2 \xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0 \xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2 \xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0View in Fusebit
\n
\n
const owner = \'stack-overflow-demos\';\n\n// For the purpose of this example, we have 1 release, so it will be always the first item.\nconst releases = await installationClient.rest.repos.listReleases({\n  owner: \'stack-overflow-demos\',\n  repo: \'private-demo\'\n});\n\n// Get release information (e.g zipball URL)\nconst release = await installationClient.rest.repos.getRelease({\n  owner: \'stack-overflow-demos\',\n  repo: \'private-demo\',\n  release_id: releases.data[0].id,\n});\n\nconst { token } = await installationClient.auth();\n\n// According to official GitHub docs https://docs.github.com/en/rest/reference/repos#download-a-repository-archive-zip\n// You will get a zipball URL you can use to download the zip file, you need to handle properly the redirects since a second GET\n// request is needed, this time with an authenticated URL.\nconst { zipball_url, tag_name } = release.data;\n\nconst response = await getZipFile(zipball_url, token);\n\n// Handle redirects properly if a responseUrl is returned that means you need to perform the redirect,\n// you don\'t need to send the access token to this request, since is a signed URL\n// Note: For private repositories, these links are temporary and expire after five minutes.\nconst {\n  request: {\n    res: { responseUrl },\n  },\n} = response;\n\nif (responseUrl) {\n  await downloadZipFile(responseUrl, `/tmp/\'${tag_name}.zip`);\n}\n\n// Get information about the zip file you\'re about to download\nconst getZipFile = async (url, token) => {\n  return await axios({\n    redirect: \'manual\',\n    method: \'get\',\n    url,\n    headers: {\n      Authorization: `token ${token}`,\n      Accept: \'application/vnd.github.v3+json\',\n    },\n  });\n};\n\n// Download the zip file from the temporary secure URL returned from the first request\nconst downloadZipFile = async (url, filePath) => {\n  const response = await axios({\n    method: \'get\',\n    url,\n    responseType: \'stream\',\n    headers: {\n      Accept: \'application/octet-stream\',\n    },\n  });\n\n  return new Promise((resolve, reject) => {\n    console.log(`writing to ${filePath}`);\n    const dest = fs.createWriteStream(filePath);\n    let progress = 0;\n    response.data\n      .on(\'end\', () => {\n        console.log(\' Done downloading file.\');\n        resolve(filePath);\n      })\n      .on(\'error\', (err) => {\n        console.error(\' Error downloading file.\');\n        reject(err);\n      })\n      .on(\'data\', (d) => {\n        progress += d.length;\n        console.log(` Downloaded ${progress} bytes`);\n      })\n      .pipe(dest);\n  });\n};\n
Run Code Online (Sandbox Code Playgroud)\n

此示例使用Octokit

\n