Search code examples
node.jsapiexpresshttp-status-code-504

Downloading an audio file with Express API and ytdl


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


Solution

  • Well for some reason the videoName was undefined so it messed up my function... Here is the correct code after a few changes and adding the destination path as query variable.

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