使用 GitHub API 進行數據分析 (Node.js)
Node.js 的訪問 GitHub 的 API 庫,通過 npm 或者 yarn 安裝:
1 yarn add github-api
官方示例
獲取 rate limit,有修改:
1 var GitHub = require('github-api'); 2 3 var gh = new GitHub( {token: "Your Token Here" } ); 4 5 /** 6 * Search API has its own rate limit other than other apis 7 */ 8 function rateLimit() { 9 // check our rate-limit status 10 // since we're unauthenticated the limit is 60 requests per hour 11 gh.getRateLimit().getRateLimit() 12 .then( function(resp) { 13 console.log('Limit remaining: ' + resp.data.rate.remaining); 14 // date constructor takes epoch milliseconds and we get epoch seconds 15 console.log('Reset date: ' + new Date(resp.data.rate.reset * 1000)); 16 }).catch( function(error) { 17 console.log('Error fetching rate limit', error.message); 18 }); 19 } 20 21 rateLimit();
在構建 GitHub 對象時,輸入用戶名及密碼,或者你在 GitHub 上申請的 Token。
申請 Token 步驟比較簡單,進入 https://github.com/settings/developers 中,選擇 Personal Access Tokens,點擊 Generate New Token,該 Token 在關閉頁面后便無法再次查看,需要將它記錄下來。
注意這里打印的 rate limit 次數是 5000/h,但它與 Search api 是有區別的。參考: https://github.com/github-tools/github/issues/487
搜索
官方示例中只有一個獲取 rate limit 的示例,如果想要使用 GitHub 提供的 Search api 對整個 GitHub 進行搜索,其實也比較簡單:
1 keyword = 'test'; 2 gh.search( {q: keyword, type: "code" } ).forCode() // * 3 .then( ( result ) => { 4 console.log( 'Processing data...' ); 5 const data = result.data; 6 if( saveFile ) { 7 console.log( 'Saving into file...' ); 8 writeJsonIntoFile( "./repos.data", data ); 9 } 10 11 for( let i = 0; i < data.length; i++ ) { 12 console.log( `Searching Page ${i+1}` ); 13 process( data[i] ); 14 } 15 16 }).catch( ( error ) => { 17 console.log( `Status ${error.response.statusText }` ) 18 console.log( `Wait ${error.response.headers.retry-after} seconds before try again.`) 19 20 writeJsonIntoFile( "./test.log", error ); 21 });
上面 * 號位置有幾個不同的接口:forCode()、forRepositories() 等等,對應着下圖中的紅色方框的位置進行的篩選:
之前提到過,這個 Search API 是有限制的,如果你過度使用的話,forCode() 中會捕獲到錯誤 error,將 error.data 打印出來:

如果出現了 abuse detection 的話,就需要等待一定時間后才能進行查詢操作,等待的時間在響應的頭部信息中:error.response.headers.retry-after。
順便一提,使用這個搜索 api 很耗時,應該是網絡的原因。
如果在對 JSON 對象做 JSON.stringify 處理時出現 converting circular structure to json 的錯誤,需要解決掉循環引用,可參考下方中提到的做法:
我將 JSON 對象的日志輸出封裝成了 writeJsonToFile 方法中。
小結
這里簡單的提到了 GitHub api 的用法和使用過程中的一些注意事項,但僅僅通過 api 獲取到了相應的數據還沒有對其進行處理。
數據的處理需要先對 Search.forCode() 方法的返回值 data 進行分析,以后再說。

