title: NodeJs - How to handle broken stream reader piped from a stream writer?
body: <p>I have an application that needs to read from a TCP socket and write to a database. It is known that, the rate of reading from TCP socket and writing to database will be different. To decouple the read and write, I am introducing a Duplex stream. Therefore, the flow is expected to be as follows.</p>
  <ol>
  <li>Read from TCP socket.</li>
  <li>Write to Duplex stream.</li>
  <li>Read from Duplex stream.</li>
  <li>Write to database.</li>
  </ol>
  <p>The question: What is the &quot;right&quot; thing to do when the database connection drops? The following options exist.</p>
  <ol>
  <li>Handle database connection drop and terminate application gracefully.</li>
  <li>Automagically redirect reads from Duplex stream (Step 3) above to a file so that, when database reconnection happens, the file <em>and</em> stream are processed. The database can tolerate &quot;past&quot; data inserts. The application is not terminated.</li>
  </ol>
  <p>Option 1 is easy but losing the TCP stream data is &quot;expensive&quot; in my use case. Option 2 does not lose TCP stream data but sounds complicated to implement.</p>
  <p>Can you please advise what is a &quot;best practice&quot;? Or, how do we implement Option 2 (at least, the redirection part)?</p>