4

I'm trying to download a Youtube video audio using the ytdl-core module (https://github.com/fent/node-ytdl-core).

I wrote an API using Express which lets me download an audio by its 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);

});

The problem is that when I call this API I get a 504 error from my server.

I want to be able to save this downloaded audio on my local disk.

Help would be appreciated. Thank you

4

1 回答 1

3

好吧,由于某种原因,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();
       });              
   });              
});
于 2016-12-12T14:27:42.770 回答