Created
February 20, 2014 00:19
-
-
Save hogedigo/9104426 to your computer and use it in GitHub Desktop.
Google Spreadsheets APIでGoogleアカウントユーザーのスプレッドシートからデータを取得する。
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
var fs = require("fs"); | |
var readline = require("readline"); | |
var gapi = require("googleapis"); | |
var CLIENT_ID = "Your client id here"; | |
var CLIENT_SECRET = "Your client secert here"; | |
var REDIRECT_URL = "Your redirect url here"; | |
var SCOPE = "https://spreadsheets.google.com/feeds"; | |
var TOKENS_FILEPATH = "./tokens.json"; | |
var rl = readline.createInterface({ | |
input: process.stdin, | |
output: process.stdout | |
}); | |
var oAuth2Client = new gapi.OAuth2Client(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL); | |
function saveToken() { | |
fs.writeFile(TOKENS_FILEPATH, JSON.stringify(oAuth2Client.credentials), function(err) { | |
if(err) { | |
console.log(err); | |
throw err; | |
} | |
}); | |
} | |
function readToken(callback) { | |
var buff; | |
try { | |
buff = fs.readFileSync(TOKENS_FILEPATH); | |
}catch(err) { | |
callback(); | |
return; | |
} | |
oAuth2Client.setCredentials(JSON.parse(buff.toString())); | |
callback(); | |
} | |
function getAccessToken(callback) { | |
var url = oAuth2Client.generateAuthUrl({ | |
access_type: "offline", | |
scope: SCOPE | |
}); | |
console.log("Visit the URL: ", url); | |
rl.question("Enter the code here: ", function(code) { | |
oAuth2Client.getToken(code, function(err, tokens) { | |
oAuth2Client.setCredentials(tokens); | |
callback(); | |
}); | |
}); | |
} | |
function getListRow(callback) { | |
var spreadsheetsKey = "Your Spreadsheets Key here"; | |
var opts = { | |
url: SCOPE + "/list/" + spreadsheetsKey + "/od6/private/basic?alt=json" | |
} | |
oAuth2Client.request(opts, callback); | |
} | |
readToken(function() { | |
var callback = function(err, body, res) { | |
if(err) { | |
console.log(err); | |
return; | |
} | |
var entry = body.feed.entry; | |
for(var i=0; i<entry.length; i++) { | |
console.log("", entry[i]); | |
} | |
} | |
if(oAuth2Client.credentials == null) { | |
getAccessToken(function() { | |
saveToken(); | |
getListRow(callback); | |
}); | |
}else { | |
getListRow(callback); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment