gpt4 book ai didi

javascript - 使用 node.js 的 YouTube 下载器

转载 作者:行者123 更新时间:2023-12-01 16:25:02 26 4
gpt4 key购买 nike

所以我正在使用 node.js 创建 YouTube 下载器。问题是在我运行代码后文件已经创建,但是文件是 0kb 并且打印成功。我想要的是当我成功下载视频时程序必须打印成功,也不能创建文件。必须在成功下载一个视频后创建文件

const playlist = [
{
title: "What is DevOps",
videoUrl: "https://www.youtube.com/watch?v=mBBgRdlC4sc",
},
{
title: "Introduction To DevOps ",
videoId: "Me3ea4nUt0U",
videoUrl: "https://www.youtube.com/watch?v=Me3ea4nUt0U",
},
{
title: "DevOps Tutorial For Beginners ",
videoId: "YSkDtQ2RA_c",
videoUrl: "https://www.youtube.com/watch?v=YSkDtQ2RA_c",
},
];
const fs = require("fs");
const ytdl = require("ytdl-core");
const length = playlist.length;

playlist.forEach((pl, i) => {
const { videoUrl, title } = pl;
const item = i + 1;

ytdl(videoUrl, {
format: "mp4",
}).pipe(fs.createWriteStream(`${title}.mp4`));
console.log(`${item}/${length} - ${title} downloaded successfully`);
});

最佳答案

在写入完成之前,您正在记录“下载成功”。你有几种可能性。一个人可能正在监听“WriterStream”上的某些事件。
来自文档:https://nodejs.org/dist/latest-v12.x/docs/api/fs.html#fs_fs_createwritestream_path_options

// Create WriteableStream
const writeableStream = fs.createWriteStream(`${title}.mp4`);

// Listening for the 'finish' event
writeableStream .on('finish', () => {
console.log(`${item}/${length} - ${title} downloaded successfully`);
});

// Plug it into the ReadableStream
ytdl(videoUrl, {
format: "mp4",
}).pipe(writeableStream);

现在这将在写入开始时创建一个新文件。我建议使用像 filename.temp.mp4 这样的临时名称。然后在写完后重命名。

关于javascript - 使用 node.js 的 YouTube 下载器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63132564/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com