0

I'm using the libraries from npm-module called ytdl-core and ffmpeg for NodeJS I have 2 functions from those modules, one is to download video and other to get audio from Youtube videos. Both functions are asynchronized, but in my algortithme one depends of the other. First, I want to download the audio, and after I want get the video of the audio source, and I don't want to execute both asynchronized, I want synchronized operation

This is my code:

var stream = app.ytdl(req.body.linkYoutube,{quality: 18});
//First, download audio
app.ffmpeg(stream)
   .audioBitrate(128)
   .save(`${__dirname}/music.mp3`)
   .on('progress', (p) => {
      app.readline.cursorTo(process.stdout, 0);
      process.stdout.write(`${p.targetSize}kb downloaded`);
   })
   .on('end', () => {
   res.status(200).download('./controllers/music.mp3');
});

//Second, download video of that audio
app.ytdl(req.body.linkYoutube, { filter : (format) => 
   format.container === 'mp4' &&
   format.qualityLabel ==='720p'// &&
   //    format.itag === 18
   })
   .pipe(app.fs.createWriteStream('video.mp4'));

I know that it's not good, but It's a good exercice to learn asynchronisme, Thanks!

Elias Arellano
  • 433
  • 5
  • 16
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – FZs Jan 10 '20 at 16:16
  • @FZs Thanks for your answer, I will check the post seriously. – Elias Arellano Jan 11 '20 at 16:54

1 Answers1

0

You can use Promise to execute the 2nd function just after the 1st finishes, like this:

  new Promise(resolve => {
    app.ffmpeg(stream)
      .audioBitrate(128)
      .save(`${__dirname}/music.mp3`)
      .on('progress', (p) => {
        app.readline.cursorTo(process.stdout, 0);
        process.stdout.write(`${p.targetSize}kb downloaded`);
      })
      .on('end', () => {
        res.status(200).download('./controllers/music.mp3');
        resolve();
      });
  }).then(() => {
    //Second, download video of that audio
    app.ytdl(req.body.linkYoutube, {
      filter: (format) =>
        format.container === 'mp4' &&
        format.qualityLabel === '720p'// &&
      //    format.itag === 18
    })
      .pipe(app.fs.createWriteStream('video.mp4'));

  }
  })
Liad Yogev
  • 854
  • 7
  • 16
  • @FZs I never said it synchronous, I proposed a possible solution as OP just needs it to work one by one. – Liad Yogev Jan 10 '20 at 19:27
  • Sure, you haven't said that it's synchronous, and your code works, but OP asked for a synchronous solution (which is btw. probably impossible to achieve). – FZs Jan 10 '20 at 19:34
  • Liad Yogev, your answer helped so much to understand promises and then() functions, thanks – Elias Arellano Jan 11 '20 at 16:59