Skip to content

Instantly share code, notes, and snippets.

@flymio
Last active March 28, 2018 05:41
Show Gist options
  • Save flymio/9d9d42eadc4a67ed438b80aa617fde57 to your computer and use it in GitHub Desktop.
Save flymio/9d9d42eadc4a67ed438b80aa617fde57 to your computer and use it in GitHub Desktop.
download files via nodejs
var rs = require('request'), max_downloaded = 5, cnt = 0, data_str = '', links = [], queue = [], finished = [], save_dir = 'tmp', fs = require('fs'), regexp = /filename=\"(.*)\"/gi;
process.stdin.on('data', function(data) {
data_str += data;
if (data_str.match("\n")){
links = data_str.split("\n").filter(url => url.length > 10);
parseLinks();
}
});
function parseLinks() {
for(var i=0; i<=links.length - 1; i++) {
//... some code here
}
}
setInterval(function () {
cnt++;
if (queue.length < max_downloaded && links.length){
var obj = {link: links.pop(), status: 'new'};
queue.push(obj);
processFile(obj, function(data){
console.log(data);
var index, founded=0;
for(var i=0; i<=queue.length-1; i++){
if (queue.url == data.url){
finished.push(data);
index = i;
founded = 1;
}
}
if (founded){
queue.splice(index, 1);
}
});
}
console.log('tic\t' + cnt + "\t" + " downloaded right now: " +queue.length + " files and "+links.length+" links");
if (!queue || queue.length == 1){
console.log(queue);
}
if (!queue || queue.length < 1){
console.log(finished);
process.exit();
}
// check workers
}, 1000);
function processFile (url, cb){
console.log('start download file', url);
url.rnd = Math.floor(Math.random()*10000);
url.file = url.link.split('\\').pop().split('/').pop();
url.status = ''
var dl = rs(url.link);
dl.on('response', function(res){
console.log(res.statusCode);
url.status = res.statusCode;
if (res.headers['content-disposition']){
url.file = regexp.exec( res.headers['content-disposition'] )[1];
}
if (url.status == 200){
console.log('success download', url.link);
url.saved_file = save_dir + "/" + url.file;
var fws = fs.createWriteStream( url.saved_file );
res.pipe( fws );
res.on( 'end', function(){
cb(url)
});
}
else{
console.log('failed download', url.link);
cb(url);
}
});
}
#!/bin/sh
echo 'var rs=require("request"); console.log(rs);'|node 2>&1|perl -ne 'chomp;if($_=~ m/cannot/i){`npm install request`}'
mkdir -p tmp
node test.js < test.links
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment