video-to-gif
Version:
A Node.js module that searches YouTube videos by song name and converts clips to animated GIFs
82 lines (70 loc) • 2.56 kB
JavaScript
import { GetListByKeyword } from 'youtube-search-api';
/**
* Search YouTube for videos by song name
* @param {string} songName - The song name to search for
* @param {number} limit - Maximum number of results to return
* @returns {Promise<Array>} Array of video objects
*/
async function searchYouTube(songName, limit = 5) {
try {
// Search YouTube
const searchResults = await GetListByKeyword(songName, false, limit);
if (!searchResults || !searchResults.items || searchResults.items.length === 0) {
console.log('No videos found in search results');
}
// Filter and format results
const videos = searchResults.items
.filter(item => item.type === 'video' && item.id && item.title)
.map(video => ({
videoId: video.id,
title: video.title,
channelTitle: video.channelTitle || 'Unknown Channel',
duration: video.length?.simpleText || video.length?.accessibility?.accessibilityData?.label || 'Unknown',
url: `https://www.youtube.com/watch?v=${video.id}`,
thumbnails: video.thumbnail?.thumbnails?.[0] || null,
viewCount: video.viewCount || 0,
uploadDate: video.publishedTimeText || 'Unknown'
}))
.filter(video => video.videoId); // Ensure we have valid video ID
if (videos.length === 0) {
console.log('No valid videos found in search results');
return null;
}
return videos;
} catch (error) {
console.log('❌ YouTube search failed:', error.message);
console.log(`Failed to search YouTube: ${error.message}`);
return null;
}
}
/**
* Extract video ID from YouTube URL
* @param {string} url - YouTube video URL
* @returns {string} Video ID
*/
function extractVideoId(url) {
try {
const regex = /(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([^&\n?#]+)/;
const match = url.match(regex);
return match ? match[1] : null;
} catch (error) {
console.log('❌ Failed to extract video ID from URL:', url);
return null;
}
}
/**
* Validate if a string contains a valid YouTube video ID
* @param {string} videoId - Video ID to validate
* @returns {boolean} True if valid
*/
function isValidVideoId(videoId) {
if (!videoId || typeof videoId !== 'string') return false;
// YouTube video IDs are typically 11 characters long and contain alphanumeric characters, hyphens, and underscores
const regex = /^[a-zA-Z0-9_-]{11}$/;
return regex.test(videoId);
}
export {
searchYouTube,
extractVideoId,
isValidVideoId
};