title: Node - Readable stream pipe() overwrite previous streams in a for loop
body: <p>I am trying to stream a data collection to multiple files with the code below:</p>
  
  <pre><code>for (var key in data) {
    // skip if collection length is 0
    if (data[key].length &gt; 0) {
      // Use the key and jobId to open file for appending
      let filePath = folderPath + '/' + key + '_' + jobId + '.txt';
  
      // Using stream to append the data output to file, which should perform better when file gets big
      let rs = new Readable();
      let n = data[key].length;
      let i = 0;
  
      rs._read = function () {
        rs.push(data[key][i++]);
  
        if (i === n) {
          rs.push(null);
        }
      };
  
      rs.pipe(fs.createWriteStream(filePath, {flags: 'a', encoding: 'utf-8'}));
  
    }
  }
  </code></pre>
  
  <p>However, I end up getting all files being populated with the same data, which is the array for the last key in <code>data</code> object. It seems the reader stream is overridden for each loop, and the <code>pipe()</code> to writable stream doesn't start until the for loop is finished. How is that possible?</p>