ReadStream and WriteStream to the same file in nodejs
<p>I create a <code>WriteStream</code> and a <code>ReadStream</code> for the same file.</p>

<p>I am testing code for persisting an object on disk.</p>

<pre><code># Code
g:(stream, cb)-&gt;
   stream.on("data", (chunk) -&gt; chunks.push(chunk))
   stream.on("end", () -&gt; cb(MyComplexObjectClass.decode(Buffer.concat(chunks)))

# Test
it "allows to persist MyComplexObject to disk", (done) -&gt;
  MyComplexObject = ... # Initialization code
  _in = fs.createWriteStream("XXX")
  out = fs.createReadStream("XXX")
  _in.write(MyComplexObject.encode())
  _in.end()
  g(out, (x) -&gt;
    # Validation of x here, should be MyComplexObject
    done()
  )
</code></pre>

<p>The test passes as is, three questions:</p>

<ul>
<li>I believe that there a race condition: when <code>end</code> is called on <code>_in</code>, the changes could potentially not be flushed to the file. How to reproduce the race condition in a test?</li>
<li>Swapping <code>_in</code> and <code>out</code>'s declarations makes the program crash with   <code>Uncaught SyntaxError: Unexpected end of input</code> although the file exists, why is that?</li>
<li>Is there a better way to implement that (still using streams)?</li>
</ul>