title: How to iterate over the following code inside a for-loop?
body: <p>I have the following code where it grabs one of the 6 URLs, strips the filename, creates a filepath, saves image file to disk, sends it off to MongoDB GridFS. The only thing that's changing is image size: 32px, 64px, 128px, 256px, 512px, 1024px. Bruteforce approach is to just copy and paste this code 6 times, and you can only imagine what a mess that would be. </p>
  
  <p>How can I place this code inside for-loop where <strong>32</strong> would change to <strong>64</strong>, <strong>128</strong>, <strong>256</strong>, <strong>512</strong>, <strong>1024</strong> for each loop iteration?</p>
  
  <pre><code>var filename32 = image32.replace(/^.*[\\\/]/, '');
  var filepath32 = path.join(__dirname, filename32);
  var writestream32 = gfs.createWriteStream({ filename: filename32 });
  var imageStream32 = request(image32).pipe(fs.createWriteStream(filepath32));
  
  imageStream32.on('close', function() {
    fs.createReadStream(filepath32).pipe(writestream32);
    fs.unlink(filepath32);
  });
  </code></pre>
  
  <h3>Update.</h3>
  
  <p>Ok so this problem is impossible to solve using iterative approach. More info here: <a href="https://stackoverflow.com/questions/12868804/node-js-while-loop-callback-not-working-as-expected">node.js: while loop callback not working as expected</a>. <strong>TLDR</strong>: Because node.js and javascript are single threaded.</p>