This repository has been archived by the owner on Nov 28, 2017. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 16
Home
Franklin van de Meent edited this page Jun 15, 2016
·
12 revisions
npm install googleapis
var google = require ('googleapis');
google.options ({ auth: 'API KEY' });
var youtube = google.youtube ('v3');
// Search Youtube -- callback is called on each found item (or error)
function search_youtube (query, callback) {
var searchParams = {
part: 'snippet',
type: 'video',
q: query,
maxResults: 50,
order: 'date',
safeSearch: 'moderate',
videoEmbeddable: true
};
youtube.search.list (searchParams, function (err, res) {
if (err) {
callback (err);
return;
}
res.items.forEach (function (result) {
var video = {
id: result.id.videoId,
urlShort: 'https://youtu.be/' + result.id.videoId,
urlLong: 'https://www.youtube.com/watch?v=' + result.id.videoId,
published: result.snippet.publishedAt,
title: result.snippet.title || '',
description: result.snippet.description || '',
images: result.snippet.thumbnails,
channelTitle: result.snippet.channelTitle,
channelId: result.snippet.channelId,
live: result.snippet.liveBroadcastContent || ''
};
// When you don't need `duration` and `definition` you can skip the section
// below to save API credits, but don't forget the `callback (null, video);`
var listParams = {
part: 'contentDetails',
id: video.id
};
youtube.videos.list (listParams, function (err2, data) {
if (err2) {
callback (err2);
return;
}
if (data.items.length) {
data.items[0].contentDetails.duration.replace (/PT(\d+)M(\d+)S/, function (t, m, s) {
video.duration = (parseInt (m, 10) * 60) + parseInt (s, 10);
});
video.definition = data.items[0].contentDetails.definition;
callback (null, video);
}
});
});
});
}
search_youtube ('running cheetah slowmotion', console.log)
{ id: 'THA_5cqAfCQ',
urlShort: 'https://youtu.be/THA_5cqAfCQ',
urlLong: 'https://www.youtube.com/watch?v=THA_5cqAfCQ',
published: '2012-12-03T15:58:45.000Z',
title: 'Cheetahs on the Edge — Director\'s Cut',
description: 'Cheetahs are the fastest runners on the planet. Combining the resources of National Geographic and the Cincinnati Zoo, and drawing on the skills of a Hollywo.',
images:
{ default: { url: 'https://i.ytimg.com/vi/THA_5cqAfCQ/default.jpg' },
medium: { url: 'https://i.ytimg.com/vi/THA_5cqAfCQ/mqdefault.jpg' },
high: { url: 'https://i.ytimg.com/vi/THA_5cqAfCQ/hqdefault.jpg' } },
channelTitle: 'NationalGeographic',
channelId: 'UCpVm7bg6pXKo1Pr6k5kxG9A',
live: 'none',
duration: 428,
definition: 'hd' }