alanshaw / stream-to-it

🚰 Convert Node.js streams to streaming iterables
Other
18 stars 6 forks source link

Add option not to destroy duplex stream when either the source or sink iterable completes #10

Open gnarea opened 4 years ago

gnarea commented 4 years ago

(First of all, stream-to-it and it-pipe are amongst my favourite NPM packages: My code would've been really complicated had you not made these packages available, so thank you so much!)

I'm implementing a WebSocket-based protocol using ws. ws offers a duplex stream to communicate with the peer and I'm wrapping that stream in a "duplex iterable" (generated by duplex()), which I pass to it-pipe.

The code mostly works as expected, but I'm running into two related issues:

I think both issues could be solved if duplex() supported an option that wouldn't call destroy()/end() on the underlying stream (maybe as a pass-through stream). That'd allow me to do something like this on the server:

const wsDuplex = WebSocket.createWebSocketStream(ws);
try {
  await pipe(loadMessages, duplex(wsDuplex, {allowClosing: false}), processAcknowledgements)

  // If we get to this point, processAcknowledgements() must've ended the loop
  ws.close(1000, 'All good')
} catch (err) {
  ws.close(1008, 'Something went wrong')
}

(duplex.end() will still be called when the connection is closed. OTOH, the example above is overly simplified: I'd probably have to use an AbortableController to signal the source of the duplex iterable when the client closes the connection.)

Thoughts?