http://localhost:3000/download?id=VIDEO_ID


http://localhost:3000/download?id=dQw4w9WgXcQ


const express = require("express");

const ytdl = require("ytdl-core");


const app = express();

const PORT = 3000;


app.get("/download", async (req, res) => {

    try {

        // Get the video ID from the query parameter

        const videoId = req.query.id;

        if (!videoId) {

            return res.status(400).json({ error: "Missing 'id' parameter" });

        }


        // Construct the YouTube URL using the provided video ID

        const videoUrl = `https://www.youtube.com/watch?v=${videoId}`;


        if (!ytdl.validateURL(videoUrl)) {

            return res.status(400).json({ error: "Invalid video ID" });

        }


        // Retrieve video information using ytdl-core

        const info = await ytdl.getInfo(videoUrl);

        const format = ytdl.chooseFormat(info.formats, { quality: "highest" });


        if (!format || !format.url) {

            return res.status(500).json({ error: "No downloadable format found" });

        }


        // Return the download link and video details in JSON

        res.json({

            title: info.videoDetails.title,

            download_link: format.url,

            format: format.mimeType,

            quality: format.qualityLabel

        });

    } catch (error) {

        console.error("Error retrieving video:", error);

        res.status(500).json({

            error: "Error retrieving video information",

            details: error.message

        });

    }

});


app.listen(PORT, () => {

    console.log(`Server is running on http://localhost:${PORT}`);

});


Comments

Popular posts from this blog

pip install pytube tqdm. pip install --upgrade pytube