javascript 使用ytdl从youtube下载音乐时出错

pu82cl6c  于 2023-04-10  发布在  Java
关注(0)|答案(1)|浏览(184)

我有这个代码:

import chalk from 'chalk'
import { randomUUID } from 'crypto'
import fs from 'fs'
import inquirer from 'inquirer'
import fetch from 'node-fetch'
import ytdl from 'ytdl-core'

process.env.YTDL_NO_UPDATE = true

function init () {
    inquirer.prompt([
        {
            name: 'videoUrl',
            message: chalk.blue('Digite a url do vídeo:'),
            prefix: '>>'
        },
    ]).then(async (answers) => {
        const regUrl = /^https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b(?:[-a-zA-Z0-9()@:%_\+.~#?&\/=]*)$/

        const url = answers.videoUrl
        if (!regUrl.test(url)) throw new Error('Url inválida!')
        if (!url.includes('youtube')) throw new Error('Url não encontrada no YouTube')

        const name = await getNameByUrlMusic(url)
        console.log(name)

        const folder = await chooseDestinationFolderForTheFiles()
        console.log(folder)

        uploadMusic(url, name, folder)
    }).catch(error => {
        console.log(chalk.red('\n', error.message, '\n'))
        init()
    })
}

async function chooseDestinationFolderForTheFiles () {
    let nameFolder = ''
    const optionsFile = ['Arquivo existente', 'Criar arquivo']

    await inquirer.prompt([
        {
            type: 'list',
            name: 'optionsFileDestination',
            message: chalk.blue('Onde enviar os arquivos?'),
            prefix: '>>',
            choices: optionsFile
        }
    ])
    .then(async res => {
        const existingFiles = []

        if (res.optionsFileDestination === optionsFile[0]) {
            const dirPath = '../Baixar-videos-YT'
            fs.readdirSync(dirPath).forEach(file => {
                if (fs.statSync(file).isDirectory() && file !== 'node_modules' && file !== '.git') {
                    existingFiles.push(file)
                }
            })
        }

        nameFolder = await definitionFile(existingFiles)
    })

    return nameFolder

}

async function definitionFile (listFileNames) {
    let nameFolder = ''
    if(listFileNames.length > 0) {
        await inquirer.prompt([
            {
                type: 'list',
                choices: listFileNames,
                message: chalk.blue('Escolha o arquivo de destino'),
                prefix: '>>',
                name: 'nameFile',
            }
        ])
        .then(res => {
            nameFolder = `./${res.nameFile}`
        })
    } else {

        let checkExistingFile = true
        while(checkExistingFile) {
            await inquirer.prompt([
                {
                    name: 'nameFile',
                    message: chalk.blue('Nome do arquivo'),
                    prefix: '>>'
                }
            ])
            .then(async (dataName) => {
                if (fs.existsSync(`./${dataName.nameFile}`)) {
                    console.log('Arquivo existente')
                    await inquirer.prompt([
                        {
                            type: 'list',
                            name: 'redirectFile',
                            message: chalk.gray('Redirecionar para o arquivo?'),
                            choices: ['Sim', 'Não']
                        }
                    ])
                    .then(res => {
                        if(res.redirectFile.toLowerCase() === 'sim') {
                            nameFolder = `./${dataName.nameFile}`
                            checkExistingFile = false
                        } else {
                            checkExistingFile = true
                        }
                    })
                } else {
                    fs.mkdirSync(`./${dataName.nameFile}`)
                    nameFolder = `./${dataName.nameFile}`
                    checkExistingFile = false 
                }
            })
        }        
    }

    return nameFolder

}

async function getNameByUrlMusic (url) {

    const response = await fetch(url)
    const html = await response.text()
    const title = html.match(/<title>(.*?)<\/title>/)[1]

    let formatTitle = 
        title
            .replace(' - YouTube', '')
            .toLowerCase()
            .replaceAll(' ', '-')
            .normalize('NFD').replace(/[\u0300-\u036f]/g, '')
            .replaceAll(/[^a-zA-Z0-9\-]+/g,'', '')
            .replaceAll('--', '-')
            .replaceAll('---', '-')

    formatTitle += `-${randomUUID().slice(0, 8)}`

    return formatTitle
}

function uploadMusic (url, name, folder) {
    const writeStream = fs.createWriteStream(`${folder}/${name}.mp3`)
    const music = ytdl(url)

    console.log(chalk.yellow('\nAguarde...\n'))

    music
        .pipe(writeStream)

    writeStream.on('finish', () => {
        console.log(chalk.green('Música baixada\n'))
        process.exit()
    })

}

init()

它一直工作到几天前,现在我开始得到这个错误,有人知道它可能是什么吗:

evalmachine.<anonymous>:25
[])||(0,c[2])((0,c[45])((0,c[25])(c[21],c[55],(0,c[11]) ()),c[2],(0,c[86])(c[55],c[53]),c[13],c[77],c[27]),c[52], c[62],c[74]),1==c[43]&&((0,c[45])((0,c[2])((0,c[13])(c[65 +Math.pow(3,2)%391],c[85]),c[78],c[35],c[68]),c[2],((0,c[76])( c[3],c[77]),c[40])(c[77]),c[40],c[87]),1)||(((((0,c[13]) (c[87],c[65]),c[52])(c[46],c[Math.pow(5,3)%149+-51]),c[47])(c[63 ],c[1]),c[62])(c[50],c[18]),c[28])(c[56],c[50])};lma(ncode);
SyntaxError: Missing catch or finally after try
    at new Script (node:vm:100:7)
    at Object.exports.decipherFormats (C:\Users\My Computer\OneDrive\Documents\Programming\Nodejs\Baixar-videos-YT\node_modules\ytdl-core\lib\sig.js:116:51)
    at runMicrotasks(<anonymous>)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async Promise.all (index 0)
    at async exports.getInfo (C:\Users\My Computer\OneDrive\Documents\Programming\Nodejs\Baixar-videos-YT\node_modules\ytdl-core\lib\info.js:401:17)
Emitted 'error' event on PassThrough instance at:
    at runMicrotasks(<anonymous>)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)`

我希望视频在最后下载,但我在try块中得到了这个错误消息,它缺少一个catch或finally,但最奇怪的是,我在代码中没有try块

cuxqih21

cuxqih211#

实际上有一个bug,临时的解决方法是:
package.json中,将需要ytdl的行改为:
"ytdl-core": "https://github.com/khlevon/node-ytdl-core.git#v4.11.3-patch.1"
这个效果很好

相关问题