承诺错误,程序打开并立即关闭

Wrong in promises, program opens and instantly closes

代码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();
        })
    })
}

代码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!')
})

为什么我编译代码的时候系统就关机了?我错过了承诺吗?

Obs:我是初学者,抱歉。

如果你想在你的模块外使用downloadAudio(),你需要导出它,否则该功能只能在模块内使用。这意味着调用 api.downloadAudioundefined 因为 downloadAudio 在模块外不存在。

所以换行

downloadAudio = link => {

exports.downloadAudio = link => {

可以在 documentation 中找到更多信息。