2

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)
        });
    });
}
1
  • They are local to that anonymous function because you used var to declare them. Commented Dec 10, 2014 at 10:42

2 Answers 2

3

You have used var to declare variable and you are declaring them inside the response event, so every-time the event is triggered there are new variables with name chunk and bar set, so they are not updating the same progress bar, instead a new progress bar is created. If you want to update the same progress bar you have two options,

  1. declare the variables without using var in them. ex. chunks = [];

    OR

  2. declare them outside of the response callback function
Sign up to request clarification or add additional context in comments.

Comments

1

These variables are defined inside your function, thus there can't be any issues or sharing between the callbacks. If you want to share some stuff between your callback, you should declare your variable outside the callback scope.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.