因此,我使用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`);
});
发布于 2020-07-28 19:09:18
在写入完成之前,您正在记录“已成功下载”。您有几种可能性。用户可能正在监听"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这样的临时名称,然后在它完成编写后重新命名。
https://stackoverflow.com/questions/63132564
复制相似问题