title: Node.js - loop through JSON list of files to save locally using http.get
body: <p>I have a JSON file that contains a list of file names on the server.  I need to loop through this list and save each file locally.  I have this working to a degree.  Sometimes it works like a charm, others it doesn't and I end up with empty files. </p>
  
  <p>I get that this is probably starting to download the next file before the previous has finished but I am struggling to re write this so that I get a callback when the file is done to start downloading the next.  I am not that experienced with client side coding and so would really appreciate some help with this.   </p>
  
  <pre><code>var filefolder = 'http://www.example.com/files/';
          var newdir = nw.App.dataPath;
          $.each(jsonFiles, function(i, fn) {
              //read and download to save locally
              var filelink = filefolder + '/' + fn;
              var newfile = fs.createWriteStream(newdir+'/files/' + '/' + fn);
              var request = http.get(filelink, function(response) {
                  response.pipe(newfile );
                  console.log(fn);
                  newfile.on('finish', function() {
                      newfile.close(cb);
                  });
              });
          });
  </code></pre>