title: Gulp task: Streams inside loop
body: <p>The point is to read all files inside <code>someFolder</code> and then injecting them in a fixed file with <code>gulp-inject-string</code> <em>using an irrelevant criteria for this question</em>.</p>
  
  <p>Some pseudo code of what I have: </p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>var gulp = require('gulp');
  var inject = require('gulp-inject-string');
  var fs = require("fs");
  
  gulp.task('compile', function() {
    
   /* reading the file names in the directory */
   var fileNames = fs.readdirSync('someFolder', 'utf8');
   fileNames.forEach(function(fileName) {
        
    /* getting the whole file content and then removing what 
    I don't want to be injected with a regex */
    var wholeFile = fs.readFileSync('someFolder/' + fileName, 'utf8');
    var file = wholeFile.replace(/&lt;!-- COMMENT-WITH-SOME-FIXED-STRING:. * --&gt;[\r\n]/g, '');
        
    /* now getting into mainFile to inject this file */
    gulp.src('mainFolder/mainFile.html')
          
    /* injecting the content after it has been processed by the regex exactly where I need it
    (which depends on the fileName I got earlier) */
    .pipe(inject.afterEach('&lt;!-- COMMENT-WITH-SOME-FIXED-STRING+FILENAME: ' + fileName + ' --&gt;', file))
    .pipe(gulp.dest('mainFolder'));
        
   });
  });</code></pre>
  </div>
  </div>
  </p>
  
  <p>This works correctly if I only have 1 file inside <code>someFolder</code>, otherwise it only injects the last read file.</p>
  
  <p>I've tried to soak up the stream into an anonymous function inside a common for loop doing something like: </p>
  
  <p><code>for(var i...){ (function(i){ /* stream stuff here*/ })(i) }</code> as I've done several times with asynchronous operations in javascript but had the exact same result.</p>
  
  <p>I also tried use <code>merge-stream</code> mapping a function over <code>fileNames</code> that returns the streams themselves and then applying the merge, but again, same result.</p>
  
  <p>What am I doing wrong while attempting to handle the streams?</p>