320x100
320x100
const fs = require('fs');
const readline = require('readline');
const { google } = require('googleapis');
const { OAuth2 } = google.auth;
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/youtube-nodejs-quickstart.json
const SCOPES = ['https://www.googleapis.com/auth/youtube.readonly'];
const TOKEN_DIR = `${
process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE
}/.credentials/`;
const TOKEN_PATH = `${TOKEN_DIR}youtube-nodejs-quickstart.json`;
/**
* Store token to disk be used in later program executions.
*
* @param {Object} token The token to store to disk.
*/
function storeToken(token) {
try {
fs.mkdirSync(TOKEN_DIR);
} catch (err) {
if (err.code !== 'EEXIST') {
throw err;
}
}
fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
if (err) throw err;
console.log('Token stored to ', TOKEN_PATH);
});
}
/**
* Lists the names and IDs of up to 10 files.
*
* @param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/
function getChannel(auth) {
const service = google.youtube('v3');
service.channels.list(
{
auth,
part: 'snippet,contentDetails,statistics',
forUsername: 'GoogleDevelopers',
},
(err, response) => {
if (err) {
console.log('The API returned an error: ', err);
return;
}
const channels = response.data.items;
if (channels.length === 0) {
console.log('No channel found.');
} else {
console.log(
"This channel's ID is %s. Its title is %s, and it has %s views.",
channels[0].id,
channels[0].snippet.title,
channels[0].statistics.viewCount,
);
}
},
);
}
/**
* 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 to call with the authorized
* client.
*/
function getNewToken(oauth2Client, callback) {
const oauth2Client1 = oauth2Client;
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) {
console.log('Error while trying to retrieve access token', err);
return;
}
oauth2Client1.credentials = token;
storeToken(token);
callback(oauth2Client);
});
});
}
/**
* 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 clientSecret = credentials.installed.client_secret;
const clientId = credentials.installed.client_id;
const redirectUrl = credentials.installed.redirect_uris[0];
const oauth2Client = new OAuth2(clientId, clientSecret, redirectUrl);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, (err, token) => {
if (err) {
getNewToken(oauth2Client, callback);
} else {
oauth2Client.credentials = JSON.parse(token);
callback(oauth2Client);
}
});
}
// Load client secrets from a local file.
fs.readFile('client_secret.json', (err, content) => {
if (err) {
console.log('Error loading client secret file: ', err);
return;
}
// Authorize a client with the loaded credentials, then call the YouTube API.
authorize(JSON.parse(content), getChannel);
});
: Youtube Data API v3의 공식문서에 나온 quick start 소스코드를 AirBnb ESLint에 맞게 수정하였다.
: 위 코드를 실행하면 client_secret.json 파일이 없다고 나오는데, 공식문서를 참고하여 만들고
파일을 알맞은 경로에 놓도록 하자
- Client_secret 토큰 생성하기
: https://developers.google.com/youtube/registering_an_application
※ Youtube Data API v3 공식문서
: https://developers.google.com/youtube/v3/quickstart/nodejs
300x250
728x90
'Programming > NodeJS' 카테고리의 다른 글
nodeJS에서 axios를 활용하여 SOAP 통신하기 (NodeJS Soap Client) (0) | 2022.05.29 |
---|---|
NodeJS와 ExpressJS에 대해서 (0) | 2022.05.05 |
노드 개발자라면 알아야할 NodeJS 라이브러리와 패키지 (0) | 2022.02.26 |
개발자가 알아야 하는 4가지 node.js 디자인 패턴 (0) | 2022.02.26 |
nodeJS 프로젝트에 logger 적용 (0) | 2022.01.30 |