UNPKG

video-to-gif

Version:

A Node.js module that searches YouTube videos by song name and converts clips to animated GIFs

50 lines (38 loc) 1.55 kB
import youtubedl from "youtube-dl-exec"; import path from "path"; import fs from "fs"; // Point to the file in the root directory const BINARY_PATH = path.resolve("./yt-dlp"); async function downloadVideo(title, outputDir, url) { if (!fs.existsSync(BINARY_PATH)) { console.error("❌ yt-dlp binary is missing!"); return null; } const outputTemplate = path.join(outputDir, `${sanitizeFilename(title)}.%(ext)s`); const cookiePath = path.resolve("cookies.txt"); // ✅ THE MAGIC CONFIGURATION FOR 2025 await youtubedl(url, { execPath: BINARY_PATH, output: outputTemplate, // 1. Use the TV Embedded client (Bypasses most 'Sign in' checks) extractorArgs: "youtube:player_client=tv_embedded", // 2. Add Referer to look like an embedded video referer: "https://www.youtube.com/", // 3. Standard flags format: "bestaudio/best", noWarnings: true, noCheckCertificates: true, forceIpv4: true, // 4. Use cookies if they exist cookies: fs.existsSync(cookiePath) ? cookiePath : undefined }); // Check if file exists const files = fs.readdirSync(outputDir).filter(f => f.startsWith(sanitizeFilename(title))); if (!files.length) return null; // Return newest file return path.join(outputDir, files[0]); } function sanitizeFilename(name) { return name.replace(/[^\w\s]/gi, '').replace(/\s+/g, '_').substring(0, 50); } export { downloadVideo };