const express = require('express');
const cors = require('cors');
const ytdl = require('ytdl-core');
const app = express();
// Middleware
app.use(cors());
app.use(express.json());
// Serve HTML frontend
app.get('/', (req, res) => {
res.send(`
YT Downloader
`);
});
// API endpoint
app.get('/api/download', async (req, res) => {
try {
const { url, format } = req.query;
if (!ytdl.validateURL(url)) {
return res.status(400).json({ error: 'Invalid YouTube URL' });
}
const info = await ytdl.getInfo(url);
const formatFilter = format === 'mp3' ? 'audioonly' : 'videoandaudio';
const formats = ytdl.filterFormats(info.formats, formatFilter);
if (formats.length === 0) {
return res.status(400).json({ error: 'No formats available' });
}
res.json({ downloadLink: formats[0].url });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Start server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`
Server running on http://localhost:${PORT}
Required packages: express cors ytdl-core
Install with: npm install express cors ytdl-core
`));