July 2017
Intermediate to advanced
656 pages
16h 1m
English
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) ...