从GitHub repo下载单个文件有哪些技巧?

我不想要显示原始文件的URL;对于二进制文件,什么都没有。

http://support.github.com/discussions/feature-requests/41-download-single-file

是否有可能将GitHub用作“下载服务器”?

如果我们决定切换到GoogleCode,是否提供了上述功能?

或者开源项目是否有免费托管和VCS?


当前回答

或者试试这个

const https = require('https');
const fs = require('fs');
const DOMAIN = 'raw.githubusercontent.com';

function writeFile(data, fileName) {
  fs.appendFile(fileName, data.toString(), err => {
    if (err) {
      console.log('error in writing file', err);
    }
  });
}

function EOF(data) {
  console.log('EOF');
}

function getFileName(pathToFile) {
  var result = pathToFile.split('/');
  var splitLength = result.length;
  return result[splitLength - 1];
}
function getFile(branchName, username, repoName, ...pathToFile) {
  pathToFile.forEach(item => {
    const path = `/${username}/${repoName}/${branchName}/${item}`;
    const URL = `${DOMAIN}${path}`;
    const options = {
      hostname: DOMAIN,
      path: path
    };
    var fileName = getFileName(item);

    https
      .get(options, function(res) {
        console.log(res.statusCode);
        /* if file not found */
        if (res.statusCode === 404) {
          console.log('FILE NOT FOUND');
        } else {
          /* if file found */
          res.on('data', data => writeFile(data, fileName));
          res.on('end', data => EOF(data));
        }
      })
      .on('error', function(res) {
        console.log('error in reading URL');
      });
  });
}
getFile('master', 'bansalAyush', 'InstagramClone', '.babelrc', 'README.md');

其他回答

为了跟进thomasfuchs所说的,但对于GitHub Enterprise用户,您可以使用以下内容。

curl-H'授权:令牌INSERTACCESSTOKENHERE'-H'接受:application/vnd.github.v3.raw'-O-Lhttps://your_domain/api/v3/repos/owner/repo/contents/path

这里还有API文档https://developer.github.com/v3/repos/contents

转到要下载的文件。单击它可查看GitHub UI中的内容。在右上角,右键单击“原始”按钮。另存为。。。

现在,这在GitHub中可以用于任何文件。您需要翻译raw.github.com的文件。例如,如果您的文件位于存储库中:

https://github.com/<username>/<repo>/some_directory/file.rb

使用wget,您可以从以下位置获取原始文件:

https://raw.github.com/<username>/<repo>/<branch>/some_directory/file.rb

Rails Composer就是一个很好的例子。

请使用“{host}/{user}/}repo}/branch}/{file}”的模式。要获得具体示例,请在Python中执行以下操作:

import pandas as pd
host = 'raw.github.com'
user = 'fivethirtyeight'
repo = 'data'
branch = 'master'
file = 'births/US_births_2000-2014_SSA.csv'
url = f'https://{host}/{user}/{repo}/{branch}/{file}'
df = pd.read_csv(url,sep=',',header=0)
df.head()

Git不支持下载部分存储库。你必须下载所有这些。但你应该能够使用GitHub完成这项工作。

当您查看文件时,它有一个指向“原始”版本的链接。URL的构造如下

https://raw.githubusercontent.com/user/repository/branch/filename

通过填写URL中的空白,您可以使用Wget或cURL(带有-L选项,请参见下文)或任何方式下载单个文件。同样,这样做不会得到Git使用的任何好的版本控制功能。

更新:我注意到你提到这不适用于二进制文件。您可能不应该在Git存储库中使用二进制文件,但GitHub为每个存储库提供了一个下载部分,您可以使用它来上传文件。如果需要多个二进制文件,可以使用.zip文件。下载上载文件的URL为:

https://github.com/downloads/user/repository/filename

请注意,上面从github.com上的链接中给出的URL将重定向到raw.githubusercontent.com。您不应该直接使用此HTTP 302重定向所提供的URL,因为根据RFC 2616:“由于重定向有时可能会更改,因此客户端应继续使用请求URI进行未来请求。”