npm install express ytdl-core fs
const express = require("express");
const ytdl = require("ytdl-core");
const fs = require("fs");
const app = express();
const PORT = 3000;
// Set default video quality (change itag if needed)
const VIDEO_ITAG = "248"; // 1080p WebM
app.get("/download", async (req, res) => {
try {
let videoInput = req.query.video;
if (!videoInput) {
return res.status(400).json({ error: "Missing 'video' parameter" });
}
// If only video ID is given, construct the full URL
if (!videoInput.startsWith("http")) {
videoInput = `https://www.youtube.com/watch?v=${videoInput}`;
}
// Validate URL
if (!ytdl.validateURL(videoInput)) {
return res.status(400).json({ error: "Invalid YouTube video ID or URL" });
}
// Get video info
const info = await ytdl.getInfo(videoInput);
const format = ytdl.chooseFormat(info.formats, { quality: VIDEO_ITAG });
if (!format || !format.url) {
return res.status(500).json({ error: "No downloadable format found" });
}
// Prepare filename
const outputFilePath = `${info.videoDetails.title.replace(/[/\\?%*:|"<>]/g, "")}.${format.container}`;
const outputStream = fs.createWriteStream(outputFilePath);
// Download video
ytdl.downloadFromInfo(info, { format }).pipe(outputStream);
outputStream.on("finish", () => {
console.log(`Downloaded: ${outputFilePath}`);
});
// Return JSON response
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}`);
});
http://localhost:3000/download?video=https://www.youtube.com/watch?v=dQw4w9WgXcQ
Comments
Post a Comment