Skip to content

Instantly share code, notes, and snippets.

@amjd
Created August 20, 2014 12:57
Show Gist options
  • Save amjd/d86f22dfac918f2f95e8 to your computer and use it in GitHub Desktop.
Save amjd/d86f22dfac918f2f95e8 to your computer and use it in GitHub Desktop.
// #!/usr/bin/env node
var spawn = require('child_process').spawn;
var path = require('path');
var url = require('url');
var dl_url = process.argv[2],
fileName = decodeURIComponent(path.basename(url.parse(dl_url).pathname)),
dest = process.argv[3] || process.cwd(),
combinedFileName = path.join(dest,fileName),
params = ['-o '+combinedFileName, '-L', '-C -', dl_url],
speeds = [],
alive = false;
function speedCheck(speed) {
if (speeds.length < 3) {
speeds.push(speed);
return true;
}
else {
speeds.reverse().pop();
speeds.reverse();
speeds.push(speed);
//Check if last 3 speeds are zero
if (speeds[0] != 0 && speeds[1] != 0 && speeds[2] != 0)
alive = true;
return alive;
}
}
//Spawning the process for the first time.
var child = spawn('curl',params);
console.log("Download started...........\n");
child.stdout.on('data', function(data) {
console.log("Stdout received.............")
//Break the output into an array of lines.
var output_lines = data.split('\n');
//Get the line which shows the speed. It will be 3rd line when starting download and 4th line while resuming.
//I don't know what I'm doing here. Probably trying to get whichever is the last line of output
var speed_line = output_lines[3] || output_lines[2] || output_lines[1] || output_lines[0];
//Extract the speed part. It will be the last number in the line.
var speed = Number(speed_line.trim().split(' ').reverse()[0]);
//Some output for debugging
console.log(data + "\n---------\nSPEED: " + speed);
//If speedCheck() returns false, it implies the last 3 speeds were zero, hence the connection was dropped.
//Restart the download by respawning the process.
if (!speedCheck(speed)) {
child.kill('SIGINT');
console.log("\nResuming download........\n");
child = spawn('curl',params);
}
});
child.on('exit',function(code, signal){
if (code == 0)
console.log('\n\nDOWNLOAD COMPLETE.\n');
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment