Previous recipes in this chapter have alluded to streams. We'll be studying these in depth in Chapter 4, Using Streams.
However, we would be remiss if we didn't mention that TCP sockets implement the streams interface.
In our main recipe, the client.js file contains the following code:
socket.on('data', (data) => {
console.log(data.toString())
})
We can write this more succinctly like so:
socket.pipe(process.stdout)
Here we pipe from the socket to STDOUT (see the first recipe of this chapter, Interfacing with standard I/O).
In fact, sockets are both readable and writable (known as duplex streams).
We can even create an echo server in one line of code:
require('net').createServer((socket) => socket.pipe(socket)).listen(1338)
The readable interface pipes directly back to the writable interface so all incoming data is immediately written back out.
Likewise, we can create a client for our echo server in one line:
process.stdin.pipe(require('net').connect(1338)).pipe(process.stdout)
We pipe standard input (STDIN) through a socket that's connected to our echo server and then pipe anything that comes through the socket to standard output (STDOUT).