반응형
이번 글은 node.js를 이용하여 유튜브 정보를 다루는 내용입니다.
https://developers.google.com/youtube/v3/quickstart/nodejs
위의 사이트에서 youtube api 이용 관련 내용을 확인할 수 있습니다.
해당 api를 통해 검색 엔진 등 다양한 정보를 출력할 수 있는 기능을 이용하실 수 있습니다.
그런데 저는 유튜브 주소를 입력 시, 해당 메인 이미지, 조회수 등 특정 정보를 얻는 것이 목적이기에 다른 npm을 이용하였습니다.
npm install youtube-info
youtube-info를 이용하여 내용을 가져오려 합니다.
해당 npm 이용 시, 아래의 정보를 다룰 수 있습니다.
{
videoId: '{video Id}',
url: '{video url}',
title: '{video title}',
description: '{video description as HTML}',
owner: '{video owner}',
channelId: '{owner channel id}',
thumbnailUrl: '{video thumbnail url}',
embedURL: '{video embed url}',
datePublished: '{video publication date}',
genre: '{video genre}',
paid: {true/false},
unlisted: {true/false},
isFamilyFriendly: {true/false},
duration: {video duration in seconds},
views: {number of views},
regionsAllowed: [ '{two letter country code}', ... ],
commentCount: {number of comments},
likeCount: {number of likes},
dislikeCount: {number of dislikes},
channelThumbnailUrl: {channel thumbnail url}
}
유튜브를 접속하시면 보통 아래와 같은 주소를 확인할 수 있습니다. (아래는 저번에 만든 ucc...)
https://www.youtube.com/watch?v=7Sq49-uDFWs
저는 데이터베이스에 ' 7Sq49-uDFWs ' 값만 저장했습니다.
이를 기반으로 정보를 출력해봅시다.
// youtube_service.js
const pool = require("../../config/database");
module.exports = {
getYoutube: callBack => {
pool.query(
`select address from youtube`,
[],
(error, results, fields) => {
if (error) {
return callBack(error);
}
return callBack(null, results);
}
);
}
}
service.js 파일에서는 단순 address만 가져옵니다.
// youtube_controller.js
const { getYoutube } = require("./youtube_service");
var forEach = require('async-foreach').forEach;
var fetchVideoInfo = require('youtube-info');
module.exports = {
getYoutube: (req, res) => {
getYoutube ((err, results) => {
var TV = new Array();
var num = 0;
forEach(results, function (item, index) {
var key = results[index].address;
fetchVideoInfo(key).then(function (videoInfo) {
TV.push({"address": "https://www.youtube.com/watch?v=" + key, "view": videoInfo.views,
"image": videoInfo.thumbnailUrl, "date": videoInfo.datePublished });
num++;
if (num == results.length) {
return res.json({
sucess: 1,
data: TV
});
}
});
});
});
},
}
// youtube_router.js
const { getYoutube } = require("./youtube_controller");
const router = require("express").Router();
router.get("/mimotv", getYoutube);
module.exports = router;
마지막으로 라우터입니다.
이후 메인 app.js 라우터만 연결해주면 됩니다.
반응형