title: Add a mongo request into a file and archive this file
body: <p>I'm having some troubles while trying to use streams with a MongoDB request. I want to : </p>
  
  <ol>
  <li>Get the results from a collection </li>
  <li>Put this results into a file</li>
  <li>Put this file into a CSV</li>
  </ol>
  
  <p>I'm using the <a href="https://www.npmjs.com/package/archiver" rel="nofollow">archiver package</a> for the file compression. The file contains csv formatted values, so for each row I have to parse them in the CSV format.</p>
  
  <p>My function take a res (output) parameters, which means that I can send the result to a client directly. For the moment, I can put this results into a file without streams. I think I'll get memory troubles for a large amount of data that's why I want to use streams.</p>
  
  <p>Here is my code (with no stream)</p>
  
  <pre><code>function getCSV(res,query) {
  
    &lt;dbRequest&gt;.toArray(function(err,docs){
      var csv = '';
      if(docs !== null){
          for(var i = 0; i&lt; docs.length; i++){
              var line = '';
  
              for(var index in docs[i]){
                  if(docs[i].hasOwnProperty(index) &amp;&amp; (index !== '_id' ) ){
  
                      if(line !== '') line+= ',';
  
                      line += docs[i][index];
                  }
              }
  
                  console.log("line",line);
  
              csv += line += '\r\n';
          }
  
      }
  }.bind(this));
  
      fileManager.addToFile(csv);
  
      archiver.initialize();
      archiver.addToArchive(fileManager.getName());
      fileManager.deleteFile();
  
      archiver.sendToClient(res);
  };
  </code></pre>
  
  <p>Once the csv is completed, I had it to a file with a Filemanager Object. The latter one handles file creation and manipulation. The addToArchive method add the file to the current archive, and the sendToClient method send the archive through the output (res parameter is the function).</p>
  
  <p>I'm using Express.js so I call this method with a server request. </p>
  
  <p>Sometimes the file contains data, sometimes it is empty, could you explain me why ?
  I'd like to understand how streams works, how could I implement this to my code ?</p>
  
  <p>Regards</p>