title: How do I download a bunch of files from a remote server, and concatenate them in a certain order using Node.js?
body: <p>I'm trying to read the contents of a bunch of javascript files on a server, and then concatenate them into a new local file. The files have to be concatenated in a specific order (specified in an array). Here's what I have so far:</p>
  
  <pre><code>var http = require('http');
  var fs = require('fs');
  
  var commonWebFiles = getCommonWebDependenciesInOrder();
  var fileContents = [];
  var path = '/folder/';
  
  fs.mkdir("target");
  for(var i = 0, l = commonWebFiles.length; i &lt; l; ++i){
      getFileContents(path, commonWebFiles[i]);
  }
  
  function getCommonWebDependenciesInOrder(){
      //Hit manager to get an correctly ordered array of common web dependencies
      //Stub
      return [
          'file1.js',
          'file2.js',
          'file3.js'
      ];
   };
  
  function getFileContents(path, filename){
      var contents = "";
      var writeStream = fs.createWriteStream("target/" + filename, {'flags': 'a'});
      var options = {
          host: 'ahost.net',
          port: 80,
          path: path + filename
      };
      var req = http.get(options, function(res) {
           res.on('data', function(chunk) {
               contents += chunk;
      });
      res.on('end', function() {
          writeStream.write(contents, encoding='binary');
          writeStream.end();
          fileContents[filename] = contents;
  
       });
  
       }).on('error', function(e) {
           console.log("Got error: " + e.message);
       });
  };
  </code></pre>
  
  <p>This downloads the files and recreates them locally, but it seems a little clunky. When I tried to just write a single file directly from a looped set of requests, I got the chunks out of order....I feel like there must be an easier way....</p>
  
  <p>Thanks in advance.</p>