Been playing around trying to get a simple youtube downloader working with ytdl-core & nextjs.
I have an onClick handler, making a call to the api.
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 appears it returns the response immediately, before the socket finishes.
I notice that if I move the response return to the .on("finish"...
, it throws a headers error.
The onClick handler first logs a promise under "resBlob"
, then logs a blob with size: 15, type: "text/plain
. I'm not sure where to go from here.
Tried returning the response on the socket on.("finish"...
.
I want to be able to return a response to the frontend and then with that response, to download the video.