在继续代码之前,如何完成 ytdl-core 下载
How can I make the ytdl-core download complete before continuing with the code
if (message.body.indexOf('/yt') != -1) {
const url = message.body.replace('/yt ', '')
await ytdl(url).pipe(fs.createWriteStream('video.mp4'))
// the code below does not wait for the download to finish
const media = MessageMedia.fromFilePath('./video.mp4')
client.sendMessage(message.from, media, { sendMediaAsDocument: true })
}
我希望 ytdl-core 在 运行 剩余代码之前完成下载。
下载完成后,会触发close
事件。您可以收听 close
事件。但是,你必须将它包装成一个 Promise,然后 await
on the promise。
if (message.body.indexOf('/yt') != -1) {
const url = message.body.replace('/yt ', '')
await new Promise((resolve) => { // wait
ytdl(url)
.pipe(fs.createWriteStream('video.mp4'))
.on('close', () => {
resolve(); // finish
})
})
// the code below does not wait for the download to finish
const media = MessageMedia.fromFilePath('./video.mp4')
client.sendMessage(message.from, media, { sendMediaAsDocument: true })
}
if (message.body.indexOf('/yt') != -1) {
const url = message.body.replace('/yt ', '')
await ytdl(url).pipe(fs.createWriteStream('video.mp4'))
// the code below does not wait for the download to finish
const media = MessageMedia.fromFilePath('./video.mp4')
client.sendMessage(message.from, media, { sendMediaAsDocument: true })
}
我希望 ytdl-core 在 运行 剩余代码之前完成下载。
下载完成后,会触发close
事件。您可以收听 close
事件。但是,你必须将它包装成一个 Promise,然后 await
on the promise。
if (message.body.indexOf('/yt') != -1) {
const url = message.body.replace('/yt ', '')
await new Promise((resolve) => { // wait
ytdl(url)
.pipe(fs.createWriteStream('video.mp4'))
.on('close', () => {
resolve(); // finish
})
})
// the code below does not wait for the download to finish
const media = MessageMedia.fromFilePath('./video.mp4')
client.sendMessage(message.from, media, { sendMediaAsDocument: true })
}