Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member
In some cases, you don't necessarily want to directly handle the data coming from a stream. You just want to send it somewhere else. This is possible using a pipe. In this video, we'll pipe incoming data into another stream. Let's go to the exercise files. Go to chapter nine, video four, and then copy the files to the desktop. Now let's have a look at pipe.js. On line one, we're requiring the file system module. Then on lines three and four you'll notice we're creating a read stream and a write stream.
We're going to pipe all of the data from the readable stream into the writable stream. This is going to create a copy of the data. Now, next there are two calls to stream.pipe. The first one is sending all the data to process.stdout. This is going to output all of the contents on the terminal screen. Now, the second one pipes the data to the writable stream we just created. This is going to copy all the data from the readable stream to the file on the other end of the writable stream.
Again, these streams are not holding all the data in memory. Its being handled in chunks behind the scenes, even though we aren't handling them directly here. So lets run the file now. Go to terminal and change directory to the desktop, that's with a capital D. And now type node and pipe.js. All of the data made it onto the screen, and now we have a copy.json file. This copy.json file is the exact same as the data.json file. To show that that's the case, I'm going to use the dif command.
Dif is going to show us all the changes, if any, between the two files. So I'm going to type dif, space, and then data.json. And then another space and then copy.json. And then I'm going to press return. So there is no difference between those two files. Readable streams can be piped into writable streams. This can simplify data processing if you just need to move data from one place to another. In the next video we will work with streams that are both readable and writable.
Get unlimited access to all courses for just $25/month.Become a member