Downloading Mp3 file from remote. Node js

12,025

The problem here is that http doesn't follow redirects. You can use the request npm module that does it by default to avoid handling headers yourself.

var fs = require('fs'),
  request = require('request');

request
  .get('http://foo.com/bar.mp3')
  .on('error', function(err) {
    // handle error
  })
  .pipe(fs.createWriteStream('2.mp3'));
Share:
12,025
Kishore Indraganti
Author by

Kishore Indraganti

Updated on June 27, 2022

Comments

  • Kishore Indraganti
    Kishore Indraganti about 2 years

    I am trying to download a mp3 file from the remote url using node js. For that I am using the following code. But It doesn't work (File that downloading having 0 bytes only its not playing once it downloaded).

    var http = require('http');
    var fs = require('fs');
    var url = "http://play.publicradio.org/rivet/d/podcast/marketplace/segments/2015/09/28/mp_20150928_seg_01_64.mp3";
    var dest = "2.mp3";
    var file = fs.createWriteStream(dest);
    var request = http.get(url, function(response) {
        console.log("res "+response);
        response.pipe(file);
        file.on('finish', function() {
            console.log("File download Completed");
        });
    }).on('error', function(err) { // Handle errors
    
    });
    
  • Mr. B.
    Mr. B. over 7 years
    I was trying to save the response via fs.writeFile(), which damaged the file. You answer is simple and good. Thank you very much!
  • TOPKAT
    TOPKAT over 3 years
    Hi request npm module is now deprecated