【问题标题】:Downloading an audio file with Express API and ytdl使用 Express API 和 ytdl 下载音频文件
【发布时间】:2017-04-26 19:31:42
【问题描述】:

我正在尝试使用 ytdl-core 模块 (https://github.com/fent/node-ytdl-core) 下载 Youtube 视频音频。

我使用 Express 编写了一个 API,让我可以通过 URL 下载音频:

app.get('/api/downloadYoutubeVideo', function (req, res) {
   res.set('Content-Type', 'audio/mpeg');       

   var videoUrl = req.query.videoUrl;   
   var videoName;

   ytdl.getInfo(videoUrl, function(err, info){
        videoName = info.title.replace('|','').toString('ascii');
        res.set('Content-Disposition', 'attachment; filename=' +    videoName + '.mp3');    
   });  

   var videoWritableStream = fs.createWriteStream('C:\\test' + '\\' +   videoName); // some path on my computer (exists!)
   var videoReadableStream = ytdl(videoUrl, { filter: 'audioonly'});

   var stream = videoReadableStream.pipe(videoWritableStream);

});

问题是,当我调用此 API 时,我的服务器收到 504 错误。

我希望能够将此下载的音频保存在我的本地磁盘上。

我们将不胜感激。谢谢

【问题讨论】:

    标签: node.js api express http-status-code-504


    【解决方案1】:

    好吧,由于某种原因,videoName 未定义,所以它弄乱了我的功能...... 这是经过一些更改并将目标路径添加为查询变量后的正确代码。

    app.get('/api/downloadYoutubeVideo', function (req, res) {  
       var videoUrl = req.query.videoUrl;   
       var destDir = req.query.destDir; 
    
       var videoReadableStream = ytdl(videoUrl, { filter: 'audioonly'});
    
       ytdl.getInfo(videoUrl, function(err, info){
           var videoName = info.title.replace('|','').toString('ascii');
    
           var videoWritableStream = fs.createWriteStream(destDir + '\\' + videoName + '.mp3'); 
    
           var stream = videoReadableStream.pipe(videoWritableStream);
    
           stream.on('finish', function() {
               res.writeHead(204);
               res.end();
           });              
       });              
    });
    

    【讨论】:

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