Search code examples
javascriptnode.jsaudio

How to download audio file from URL in Node.js?


How to download audio file from URL and store it in local directory? I'm using Node.js and I tried the following code:

var http = require('http');
var fs = require('fs');
var dest = 'C./test'
var url= 'http://static1.grsites.com/archive/sounds/comic/comic002.wav'
function download(url, dest, callback) {
  var file = fs.createWriteStream(dest);
  var request = http.get(url, function (response) {
    response.pipe(file);
    file.on('finish', function () {
      file.close(callback); // close() is async, call callback after close completes.
    });
    file.on('error', function (err) {
      fs.unlink(dest); // Delete the file async. (But we don't check the result)
      if (callback)
        callback(err.message);
    });
  });
}

No error occured but the file has not been found.


Solution

  • Duplicate of How to download a file with Node.js (without using third-party libraries)?, but here is the code specific to your question:

    var http = require('http');
    var fs = require('fs');
    
    var file = fs.createWriteStream("file.wav");
    var request = http.get("http://static1.grsites.com/archive/sounds/comic/comic002.wav", function(response) {
      response.pipe(file);
    });