Trying to download from URL and save to file with node.js.. what is my issue?

I want to download specific files from a URL, but appear am having problems with only a single file being written out. The following is my code:

var filenames=["a.txt", "b.txt", "c.txt"];
for(var i in filenames) {
  var url = 'http://myhomepage/'+filenames[i];
  restler.get(url, {
    }).on('complete', function (data) {
      fs.writeFile('./'filenames[i], data, function(err, data) {
      })
    });      
  }

It seems that the only file that gets written out is "c.txt" and not the others. What is the issue and how to fix?

That is because restler.get is asynchronous and by the time the first file is being written, the for loop is on the last element. You can get around this by using a forEach and creating a separate scope for each elem you iterate over:

var filenames=["a.txt", "b.txt", "c.txt"];
filenames.forEach(function(filename) {
  var url = 'http://myhomepage/'+filename;
  restler.get(url, {
    }).on('complete', function (data) {
      fs.writeFile('./' + filename, data, function(err, data) {
      })
    });      
  }
} );

Alternatively, if you want to keep your implementation less changed, you can create a wrapper function to create a separate scope:

var filenames=["a.txt", "b.txt", "c.txt"];
for(var i in filenames) {
  (function(i) {
  var url = 'http://myhomepage/'+filenames[i];
  restler.get(url, {
    }).on('complete', function (data) {
      fs.writeFile('./'filenames[i], data, function(err, data) {
      })
    });  
  }(i));    
  }