I have this script written in javascript and node.js that downloads a bunch of files using the node.js progress and request (https://github.com/request/request) packages. Multiple requests are being fired. My question is if about the variable scope of the variables "bar" and "chunks", defined in the on('response',function) are local to that event and the on('data') event/fuction inside it, or that it is possible that multiple get requests are updating the same progress bar. I guess I am getting confused because of the asynchronous/event driven nature of node.js and javascript.
Basically this is the code:
var i;
var request = require('request').defaults({jar:true});
var ProgressBar = require('progress');
var fs = require('fs');
for (i in links){
var link = links[i];
request.get(link).on('response',function(response){
var disp = response.headers['content-disposition'];
var filename = disp.substring(disp.indexOf('filename="')+'filename="'.length,disp.length-1)
var chunks = [];
var len = parseInt(response.headers['content-length'], 10);
var bar = new ProgressBar(' downloading [:bar] :percent :etas', {total: len });
response.on('data',function(chunk){
bar.tick(chunk.length);
chunks.push(chunk);
});
response.on('end',function(){
console.log('writing file '+filename);
var file = new Buffer.concat(chunks);
f = fs.writeFileSync('/home/dolf/Documents/space_projecten/Elektor/'+filename,file)
});
});
}
varto declare them.