YouTube Video Downloader
// Install first: npm install express child_process
const express = require("express");
const { exec } = require("child_process");
const path = require("path");
const app = express();
app.use(express.json());
app.post("/download", (req, res) => {
const videoUrl = req.body.url;
if (!videoUrl) {
return res.status(400).send("No URL provided");
}
// Use yt-dlp to download best mp4 format
const output = path.join(__dirname, "video.mp4");
exec(`yt-dlp -f mp4 -o "${output}" "${videoUrl}"`, (error) => {
if (error) {
return res.status(500).send("Error downloading video");
}
res.download(output, "video.mp4");
});
});
app.listen(3000, () => {
console.log("Server running on http://localhost:3000");
});
async function downloadVideo() {
const url = document.getElementById("videoUrl").value;
const statusMsg = document.getElementById("statusMsg");
if (!url) {
statusMsg.textContent = "❌ Please enter a YouTube URL.";
return;
}
statusMsg.textContent = "⏳ Downloading...";
try {
const response = await fetch("/download", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ url }),
});
if (response.ok) {
const blob = await response.blob();
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = "video.mp4";
link.click();
statusMsg.textContent = "✅ Download started!";
} else {
statusMsg.textContent = "❌ Failed to download video.";
}
} catch (err) {
statusMsg.textContent = "⚠️ Error connecting to server.";
}
}
0 Comments