Skip to content

Instantly share code, notes, and snippets.

@falkolab
Created July 30, 2014 08:16
Show Gist options
  • Save falkolab/f160f446d0bda8a69172 to your computer and use it in GitHub Desktop.
Save falkolab/f160f446d0bda8a69172 to your computer and use it in GitHub Desktop.

Revisions

  1. falkolab created this gist Jul 30, 2014.
    50 changes: 50 additions & 0 deletions download.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,50 @@
    function download(fileUrl, apiPath, callback) {
    var url = require('url'),
    http = require('http'),
    p = url.parse(fileUrl),
    timeout = 10000;

    var file = fs.createWriteStream(apiPath);

    var timeout_wrapper = function( req ) {
    return function() {
    console.log('abort');
    req.abort();
    callback("File transfer timeout!");
    };
    };


    console.log('before');

    var request = http.get(fileUrl).on('response', function(res) {
    console.log('in cb');
    var len = parseInt(response.headers['content-length'], 10);
    var downloaded = 0;

    res.on('data', function(chunk) {
    file.write(chunk);
    downloaded += chunk.length;
    process.stdout.write("Downloading " + (100.0 * downloaded / len).toFixed(2) + "% " + downloaded + " bytes" + isWin ? "\033[0G": "\r");
    // reset timeout
    clearTimeout( timeoutId );
    timeoutId = setTimeout( fn, timeout );
    }).on('end', function () {
    // clear timeout
    clearTimeout( timeoutId );
    file.end();
    console.log(file_name + ' downloaded to: ' + apiPath);
    callback(null);
    }).on('error', function (err) {
    // clear timeout
    clearTimeout( timeoutId );
    callback(err.message);
    });
    });

    // generate timeout handler
    var fn = timeout_wrapper( request );

    // set initial timeout
    var timeoutId = setTimeout( fn, timeout );
    }