i am using ytld to download a youtube video
import fs from 'fs';
import path from 'path';
import ytdl from 'ytdl-core';
import { NextResponse } from 'next/server';
export async function POST(request: Request) {
const { url } = await request.json();
if (!url || !ytdl.validateURL(url)) {
return NextResponse.json({ error: 'Invalid URL' }, { status: 400 });
}
try {
const videoId = ytdl.getURLVideoID(url);
const info = await ytdl.getInfo(url);
const title = info.videoDetails.title.replace(/[^a-z0-9]/gi, '_').toLowerCase();
const outputPath = path.resolve('./videos', `${title}_${videoId}.mp4`);
await fs.promises.mkdir(path.resolve('./videos'), { recursive: true });
const videoStream = ytdl(url, { filter: 'audioandvideo', quality: 'highest' });
const writeStream = fs.createWriteStream(outputPath);
videoStream.pipe(writeStream);
await new Promise((resolve, reject) => {
writeStream.on('finish', resolve);
writeStream.on('error', reject);
});
return NextResponse.json({ message: 'Video downloaded successfully', filePath: outputPath }, { status: 200 });
} catch (error) {
return NextResponse.json({ error: 'Error processing request', details: (error as Error).message }, { status: 500 });
}
}
Why is this happening the video file does not open it is like the file is corrupt:
I am in a next-js application the size of the file being shown is 0 bytes it is like the API endpoint is not fetching correcly
1