Recently, I've been experimenting with setting up a basic YouTube downloader using ytdl-core & nextjs.
In my code, there's an onClick function that makes an API call.
const onClick = async () => {
await fetch("/api")
.then(async (res: any) => {
const blob = res.blob();
console.log("resBlob", blob);
return blob;
})
.then((blob: any) => console.log("BLOB", blob));
};
export async function GET(request: Request) {
const url =
"https://www.youtube.com/watch?v=r_LroCsdB20&ab_channel=riserecords";
const res = await ytdl(url)
.pipe(fs.createWriteStream("video.mp4"))
.on("finish", function () {
console.log("FINISHED");
});
return new Response(res);
}
It seems like the response is being sent back immediately, even before the socket completes.
I have noticed that if I move the response return inside the .on("finish"...
block, it throws a headers error.
When the onClick handler runs, it first logs a promise under "resBlob"
, and then it logs a blob with size: 15, type: "text/plain"
. I'm a bit stuck on where to go from here.
I've attempted to return the response within the on.("finish"...
event. My goal is to send a response to the frontend and use that response to initiate the video download.