Last active
October 7, 2017 23:04
-
-
Save magicien/c45a69faff73ba59c4392674aff39c84 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// サーバ側のコード | |
const express = require('express') | |
const fetch = require('node-fetch') | |
const app = express() | |
app.get('/githubapi/repos/:owner/:repo/:ref', (req, res) => { | |
const owner = req.params.owner | |
const repo = req.params.repo | |
const ref = req.params.ref | |
// zipballの代わりにtarballでも良い。 | |
const url = `https://api.github.com/repos/${owner}/${repo}/zipball/${ref}` | |
// プライベートなリポジトリの場合は、fetchのオプションでトークンを渡す。でも今回は省略。 | |
// 応答はダウンロードURLへのリダイレクトになるので、オプションは { redirect: 'follow' }(デフォルトのまま)にしておく。 | |
fetch(url).then((data) => { | |
res.setHeader('content-type', 'application/octet-stream') | |
data.body.pipe(res) | |
}).catch((err) => { | |
res.send(null) | |
}) | |
}) | |
// クライアント側のコード | |
import fetch from 'whatwg-fetch' | |
import JSZip from 'jszip' | |
async function downloadZip(owner, repo, ref = 'master') { | |
const url = `/githubapi/repos/${owner}/${repo}/${ref}` | |
const zipData = await fetch(url) | |
const blob = await zipData.blob() | |
return JSZip.loadAsync(blob) | |
} | |
async function getFileContent(owner, repo, filename, type = 'string') { | |
const zip = await downloadZip(owner, repo) | |
// ディレクトリ名は、"someone-greatrepo-1f2e3d4/" のようになる。 | |
const dirPattern = RegExp(`^${owner}-${repo}-[0-9a-f]+/$`) | |
const dirname = Object.keys(zip.files).find((name) => dirPattern.test(name)) | |
const filePath = `${dirname}${filename}` | |
// 指定したパスのファイルを解凍して中身を返す。 | |
// バイナリなら string の代わりに binarystring/uint8array/arraybuffer/blob とか。 | |
return zip.file(filePath).async(type) | |
} | |
getFileContent('someone', 'greatrepo', 'memo.txt') | |
.then((content) => { | |
console.log(content) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment