벌꿀오소리가 되고싶은
Google Sheets api -Node.js 본문
const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');
// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly'];
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
const TOKEN_PATH = 'token.json';
/**/
// Load client secrets from a local file.
fs.readFile('credentials.json', (err, content) => {
if (err) return console.log('Error loading client secret file:', err);
// Authorize a client with credentials, then call the Google Sheets API.
authorize(JSON.parse(content), listMajors);
});
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
* @param {Object} credentials The authorization client credentials.
* @param {function} callback The callback to call with the authorized client.
*/
function authorize(credentials, callback) {
const {client_secret, client_id, redirect_uris} = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(
client_id, client_secret, redirect_uris[0]);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, (err, token) => {
if (err) return getNewToken(oAuth2Client, callback);
oAuth2Client.setCredentials(JSON.parse(token));
callback(oAuth2Client);
});
}
// authorize()
/**
* Get and store new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
* @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
* @param {getEventsCallback} callback The callback for the authorized client.
*/
function getNewToken(oAuth2Client, callback) {
const authUrl = oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES,
});
console.log('Authorize this app by visiting this url:', authUrl);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.question('Enter the code from that page here: ', (code) => {
rl.close();
oAuth2Client.getToken(code, (err, token) => {
if (err) return console.error('Error while trying to retrieve access token', err);
oAuth2Client.setCredentials(token);
// Store the token to disk for later program executions
fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
if (err) return console.error(err);
console.log('Token stored to', TOKEN_PATH);
});
callback(oAuth2Client);
});
});
}
/**
* Prints the names and majors of students in a sample spreadsheet:
* @see https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
* @param {google.auth.OAuth2} auth The authenticated Google OAuth client.
*/
function listMajors(auth) {
const sheets = google.sheets({version: 'v4', auth});
sheets.spreadsheets.values.get({
spreadsheetId: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms',
range: 'Class Data!A2:E',
}, (err, res) => {
if (err) return console.log('The API returned an error: ' + err);
const rows = res.data.values;
if (rows.length) {
console.log('Name, Major:');
// Print columns A and E, which correspond to indices 0 and 4.
rows.map((row) => {
console.log(`${row[0]}, ${row[4]}`);
});
} else {
console.log('No data found.');
}
});
}
https://developers.google.com/drive/activity/v1/quickstart/nodejs
Node.js Quickstart | Google Drive Activity | Google Developers
Complete the steps described in the rest of this page to create a simple Node.js command-line application that makes requests to the Google Drive Activity API. Prerequisites To run this quickstart, you need the following prerequisites: Node.js & npm instal
developers.google.com
Google 공식 문서에 있는 Quickstart 코드를 긁어 와서 바로 돌려보기
노드 프로젝트 루트에
Index.js와 credentiials.json 파일을 추가 후 node . 명령어를 사용하면 authurl 경로가 나온다
해당 경로에 접속( 주의! 파랗게 액티브된 경로 뿐만아니아 밑에 한줄까지 전부 복사 해서 브라우저에 입력)
토큰 값 복사해서 터미널에 붙여 넣기!
https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit#gid=0
Example Spreadsheet
Class Data Student Name,Gender,Class Level,Home State,Major,Extracurricular Activity Alexandra,Female,4. Senior,CA,English,Drama Club Andrew,Male,1. Freshman,SD,Math,Lacrosse Anna,Female,1. Freshman,NC,English,Basketball Becky,Female,2. Sophomore,SD,Art,Ba
docs.google.com
구글 시트에 정보 를 받아 온 것을 확인 할 수 있다.
'개발 > 개발 이모저모' 카테고리의 다른 글
AWS EC2 + DOCKER + JENKINS + SPRING BOOT (0) | 2020.03.01 |
---|---|
[NCIA - 3일차] 하둡 빅데이터 분산시스템 구축 과정 (0) | 2020.02.15 |
[NCIA - 2일차] 하둡 빅데이터 분산시스템 구축 과정 (0) | 2020.02.15 |
[NCIA - 1일차] 하둡 빅데이터 분산시스템 구축 과정 (0) | 2020.02.13 |
Vuex 뷰엑스 (0) | 2020.01.21 |