mkdir youtube-downloader
cd youtube-downloader
npm init -y
npm install express ytdl-core
GET http://localhost:3000/getVideoInfo?url=YOUTUBE_VIDEO_URL
http://localhost:3000/download?url={YOUTUBE_VIDEO_URL}&itag={FORMAT_ITAG}
const express = require('express');
const ytdl = require('ytdl-core');
const cors = require('cors');
const app = express();
const PORT = 3000;
app.use(cors());
app.use(express.json());
// Endpoint to get video details and available download options
app.get('/getVideoInfo', async (req, res) => {
const videoURL = req.query.url;
if (!videoURL) {
return res.status(400).json({ success: false, message: 'YouTube video URL is required' });
}
try {
if (!ytdl.validateURL(videoURL)) {
return res.status(400).json({ success: false, message: 'Invalid YouTube video URL' });
}
const videoID = ytdl.getURLVideoID(videoURL);
const info = await ytdl.getInfo(videoID);
const formats = info.formats.map(format => ({
itag: format.itag,
quality: format.qualityLabel || 'Unknown',
mimeType: format.mimeType.split(';')[0],
hasAudio: !!format.audioBitrate,
hasVideo: !!format.qualityLabel,
container: format.container,
url: `/download?url=${videoURL}&itag=${format.itag}`
}));
res.json({
success: true,
videoDetails: {
title: info.videoDetails.title,
author: info.videoDetails.author.name,
lengthSeconds: info.videoDetails.lengthSeconds,
thumbnails: info.videoDetails.thumbnails,
},
availableFormats: formats
});
} catch (error) {
res.status(500).json({ success: false, message: 'Failed to retrieve video information', error: error.message });
}
});
// Endpoint to download the selected video format
app.get('/download', (req, res) => {
const videoURL = req.query.url;
const itag = req.query.itag;
if (!videoURL || !itag) {
return res.status(400).json({ success: false, message: 'Invalid request, YouTube video URL and itag are required' });
}
if (!ytdl.validateURL(videoURL)) {
return res.status(400).json({ success: false, message: 'Invalid YouTube video URL' });
}
try {
res.header('Content-Disposition', 'attachment; filename="video.mp4"');
ytdl(videoURL, { quality: itag }).pipe(res);
} catch (error) {
res.status(500).json({ success: false, message: 'Failed to download the video', error: error.message });
}
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Comments
Post a Comment