kennethreyt
kennethreyt

Reputation: 161

YouTube Downloader using node.js

So I'm creating YouTube Downloader using node.js. The problem is the files are already created after I ran the code, but the files are 0kb and it prints Successfully. What I want is the program must be print successfully when I successfully download the video, also must not be created the file yet. the file must be created after the one video successfully downloaded

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`);
});

Upvotes: 4

Views: 5282

Answers (1)

turbopasi
turbopasi

Reputation: 3605

You are logging "downloaded successfully" before the writing is finished. You have a few possibilities. One might be listening on certain events on the "WriterStream".

from the docs : 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);

Now this will create a new file as soon the writing starts. I suggest using a temporary name like filename.temp.mp4 and then rename it after it finished writing.

Upvotes: 2

Related Questions