Code ytdl.js
const ytdl = require('ytdl-core')
const fs = require('fs')
downloadAudio = link => {
return new Promise((resolve, reject) => {
const stream = ytdl(link).pipe(fs.createWriteStream(`musica.mp3`));
stream.on('error', () => {
console.log('Tive problemas para baixar sua música!')
reject();
})
stream.on('close', () => {
console.log('Baixado!')
resolve();
})
})
}
Code index.js
const api = require('./ytdl')
api.downloadAudio('https://www.youtube.com/watch?v=I3A45smjVo4').then(()=>{
console.log('Música baixada!')
}).catch(()=>{
console.log('Tive algum problema para baixar sua música!')
})
Why when I compile the code does the system just shut down? Am I missing promises?
Obs: I'm a beginner, sorry.
If you want to use downloadAudio()
outside your module, you need to export it, otherwise the function is only available inside the module. That means that the call api.downloadAudio
is undefined
since downloadAudio
does not exists outside the module.
So change the line
downloadAudio = link => {
to
exports.downloadAudio = link => {
More info can be found in the documentation.