【问题标题】:node-ytdl-core promise audio title and file downloadnode-ytdl-core 承诺音频标题和文件下载
【发布时间】:2017-06-04 07:14:47
【问题描述】:

我对 Promise 比较陌生,并且在使用 node-ytdl-core 时遇到了两件事。

 exports.downloadMP3 = function(bot, msg, sSuffix) {
    return Promise
    .all([
        ytdl(sSuffix, {filter : 'audioonly',}).pipe(fs.createWriteStream('audio.mp3')),
        promiseTitle(sSuffix)
    ])
    .then(function(results) {msg.channel.sendFile('audio.mp3', results[1], '', '')})
    .catch(error => console.error(error));
}

function promiseTitle(sSuffix) {
    return new Promise(function (resolve, reject) {
        ytdl.getInfo(sSuffix, function(err, info) {
            if (err) reject(err);
            console.log(info.title);
            return resolve(info.title);
        });
    });
}

当我使用上面的代码时,返回的标题是一个类似于 a25998454d48491.V 的字符串,尽管控制台记录了正确的标题。这意味着承诺不会返回我想要的值。

此外,createWriteStream 在文件被发送(sendFile)之前没有得到解决,这意味着我得到了一个 0byte 的文件,但过了一会儿文件完成下载并且在文件系统中具有正确的大小/内容。

因此,我的问题是如何在我的承诺中返回正确的值,并将 createWriteStream 变成一个承诺?

提前致谢。

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    想通了。标题很好,但 sendFile() 不允许在文件名中使用“/”。我正在测试的视频具有该字符。在下面的代码中,我设法通过使用流事件将流的所有数据附加到数组中,将 ytdl 流转换为缓冲区。可以使用另一个事件(结束事件)来最终发送您的缓冲区。

    exports.downloadMP3 = function(bot, msg, sSuffix) {
        return Promise
        .all([
            promiseTitle(sSuffix)
        ])
        .then(function(results) {
            let stream = ytdl(sSuffix, {filter : 'audioonly',});
            let aData = [];
    
            stream.on('data', function(data) {
              aData.push(data);
            });
    
            stream.on('end', function() {
                let buffer = Buffer.concat(aData);
                let title = results[0].replace(/[^a-zA-Z0-9]/g,'_');
                console.log(title);
                msg.channel.sendFile(buffer, `${title}.mp3`, '', '');
            });
        })
        .catch(error => console.error(error));
    }
    
    function promiseTitle(sSuffix) {
        return new Promise(function (resolve, reject) {
            ytdl.getInfo(sSuffix, function(err, info) {
                if (err) reject(err);
                console.log(info);
                resolve(info.title);
            });
        });
    }
    

    【讨论】:

      猜你喜欢
      • 2017-04-26
      • 2018-04-13
      • 2022-09-30
      • 2020-05-05
      • 2016-12-13
      • 1970-01-01
      • 2018-05-29
      • 2018-03-09
      • 2019-02-24
      相关资源
      最近更新 更多