Duplex Streams

In notebook:
FrontEndMasters Networking and Streams
Created at:
2017-09-24
Updated:
2017-10-01
Tags:
backend Node JS JavaScript

a.pipe(stream).pipe(a)

in this case a is a duplex stream.

Echo server example of duplex stream

  //	****		echo.js		****

const net = require('net')
// net will create a duplex stream 
// for every network connection
net.createServer(function (stream) {
  stream.pipe(stream) // you can pipe a stream into itself
  // so this will not create an infinite loop, it's decoupled
}).listen(5000) // ☛  listen...

Now it will split back the same string that you send to it.

This is a great way to demo sockets, async handling in the runtime.

Let's make an echo proxy. It will forward incoming connections.

  //	****		proxy.js		****

var net = require('net')
// need to create a server ↴
net.createServer(function (stream) {
  // on every connection we need to connect to the other side
  stream
  // we could emit `localhost` below ↴
  .pipe(net.connect(5000,'localhost'))
  // then you can pipe back ↴
  .pipe(stream)
}).listen(5005)