Make the system wait for a file to be created

Viewed 59

my code works, however, it is skipping a few steps.

Code:

link = message.body.split(' ').slice(1).join(' ')
    if(palavraChave == '/musica'){
      apiDownload.downloadAudio(link)
      await client.sendFile(message.from, 'C:/Users/mathe/Desktop/wpp/videos/musica.mp3', 'musica')
      await fs.unlinkSync('C:/Users/mathe/Desktop/wpp/videos/musica.mp3')
    }

Código apiDownload:

const ytdl = require('ytdl-core');
const fs = require('fs')

downloadAudio = (link)=>{
    ytdl(link).pipe(fs.createWriteStream(`videos/musica.mp3`), console.log('criado!'))
}

exports.downloadAudio = downloadAudio;

This code above, downloads the audio perfectly and puts it in a folder on my computer, however, when I try to send this audio that was created, the system says that it does not exist.

Note: If I run it again, then it finds the file and sends it.

That is, the problem is that the system does not wait for me to create the file and already wants to send it.

How can I make the system wait for me to create the file in my folder, after it has been created, send it?

And, after sending delete.

Can someone help me please.

I'm a beginner.

1 Answers

You need to be able to know when the file is downloaded. For this, it would be useful to make downloadAudio return a Promise. You should be able to edit it like this:

downloadAudio = link => {
  return new Promise((resolve, reject) => {
    const stream = ytdl(link, { filter: "audioonly" })
                     .pipe(fs.createWriteStream(`videos/musica.mp3`));
    stream.on("error", reject);
    stream.on("finish", () => { console.log("criado!"); resolve(); });
  });
};

And then, in your main function, add await in front of it:

await apiDownload.downloadAudio(link);
Related