title: How to wait for loop of stream.write() to end
body: <p>I am using Node's fs.WriteStream to write data into files. I am looping through an array of objects and writing each object with the <em>write()</em> function.</p>
  <p>The problem is that I would like to know once this loop is over and all the <em>write()</em> calls are done, but I cannot make it work.</p>
  <p>I've attempted a few solutions, such as not using a stream, but that would create other problems. The solution I last attempted was checking in the loop if it was the last item, and if so, closing, ending or destroying the stream.</p>
  <p>None of these worked. The event is emmited before the file is actually written.</p>
  <p>Here follows my code, and I appreciate any help I can get. Thank you very much.</p>
  <pre><code>    async function writeFile(path, data) {
  
      try {
  
          const writeStream = fs.createWriteStream(path, {
              flags: &quot;w&quot;
          })
  
          data.forEach((file, index) =&gt; {
              writeStream.write(`${file.name}\n`, (err) =&gt; {
                  if(err) throw err
                  if(index === (data.length - 1)) writeStream.end(); //I attempted close() and destroy() too, none worked
              })
          })
  
          writeStream.on(&quot;finish&quot;, () =&gt; {
              console.log(&quot;All files were written.&quot;) //Currently being emmited before all is written.
          })
  
      } catch (err) {
  
          throw (err)
      }
  }
  </code></pre>